i have an ASP.net UserControl
that requires the containing page to include a reference to jquery.
In the olden days, i would simply have included a reference to jQuery in the containing page:
<HEAD>
<SCRIPT type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></SCRIPT>
</HEAD>
But my UserControl's dependency on jQuery is an internal implementation detail, that should not be leaking to the outside. How can my userControl dictate that jQuery be included in the final page?
Researching this, i find a lot of confused solutions, calling different functions at different times. i hesitate to mention any of them, because people might think that any of them are valid. i am hoping for the correct answer, not an answer that works.
Different solutions involve calling:
- calling
this.Page.ClientScript.RegisterClientScriptInclude
duringRender
- calling
this.Page.ClientScript.RegisterStartupScript
duringRender
- calling
this.Page.ClientScript.RegisterStartupScript
duringPage_Load
- calling
this.Page.ClientScript.RegisterStartupScript
during a button click - calling
Page.Header.Controls.Add(new LiteralControl( { Text = "<script type=\"text/javascript\" src=\"...\"></script>";);
- simply including a
<SCRIPT>
element in youruserControl.ascx
file - calling
RegisterClientScriptBlock
duringOnPreRender
My confusion is centered around:
- when would i want to use
RegisterClientScriptInclude
vsRegisterStartupScript
? - when would i want to call it during
Page_Load
vsRender
vsPreRender
vs a button click? - how do i give
RegisterXxxxScriptXxx
the path to"Scripts/jquery-1.7.2.min.js"
?
Short version: How do i convert
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %><!DOCTYPE html>
<html>
<head runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
for use in a UserControl:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MySuperCoolControl.ascx.cs" Inherits="Controls_MySuperCoolControl" %>
script
tags in theheader
are horrible anti-patterns" nazi, but at a certain scale, it does make sense. – Jared Farrish May 28 '12 at 15:40Boolean
properties forRegisterYui
?RegisterDoho
?RegisterPrototype
? – Ian Boyd May 28 '12 at 15:40