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.RegisterClientScriptIncludeduringRender - calling
this.Page.ClientScript.RegisterStartupScriptduringRender - calling
this.Page.ClientScript.RegisterStartupScriptduringPage_Load - calling
this.Page.ClientScript.RegisterStartupScriptduring a button click - calling
Page.Header.Controls.Add(new LiteralControl( { Text = "<script type=\"text/javascript\" src=\"...\"></script>";); - simply including a
<SCRIPT>element in youruserControl.ascxfile - calling
RegisterClientScriptBlockduringOnPreRender
My confusion is centered around:
- when would i want to use
RegisterClientScriptIncludevsRegisterStartupScript? - when would i want to call it during
Page_LoadvsRendervsPreRendervs a button click? - how do i give
RegisterXxxxScriptXxxthe 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" %>
scripttags in theheaderare horrible anti-patterns" nazi, but at a certain scale, it does make sense.jQuerythemselves. I'm sure WebForms has a very nice intended way to handle this; i just couldn't be bothered to try to guess what it was.