Category : .Net | Author : Chtiwi Malek | First posted : 10/25/2012 | Updated : 11/30/2012
Tags : include, js, javascript, c#, .net, file, library, ajax, jquery, scripts
The best method to add JavaScript to a page footer in ASP.Net

The best method to add JavaScript to a page footer in ASP.Net

How to add JavaScript script or library to the end of an asp.net page, just before the page’s closing tags ?

I’ve received this question today on one of my tutorials, here’s a quick answer:

1/ It is better to use RegisterClientScriptInclude to include a reference to a JavaScript library (JsFile.js) :
if (!Page.ClientScript.IsClientScriptIncludeRegistered("jsFileInclude"))
Page.ClientScript.RegisterClientScriptInclude("jsFileInclude", "JsFile.js");
The JavaScript library reference will be added at the beginning of the document just after the viewstate data.

2/ To inject some JavaScript code into the page, you can use the RegisterStartupScript method :
string jsCodeBlock = "var MyStr='here'; alert(MyStr);";

if (!Page.ClientScript.IsStartupScriptRegistered("myJsCode"))
Page.ClientScript.RegisterStartupScript(typeof(string), "myJsCode", jsCodeBlock, true);
The Javascript code will be added at the end of the document.

When the last parameter is set to true the .net framework will add automatically the opening and closing script tags (or merge the code with other generated JavaScript code under the same script tags). Also the code will be written as it is at the end of the document.

But also we can use the RegisterStartupScript method to include a reference to a JavaScript library at the end of the document, we write the full reference to the JS file and set the last parameter to false :
string jsFile = "<script src=\"JsFile.js\" Type=\"text/javascript\"></script>";

if (!Page.ClientScript.IsStartupScriptRegistered("myJsFileRef"))
Page.ClientScript.RegisterStartupScript(typeof(string), "myJsFileRef", jsFile, false);
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :