Best practices for adding JavaScript to the bottom of the ASP.Net page

  • 2020-05-26 08:12:29
  • OfStack

How do I add an JavaScript script or library to the end of the asp.net page, before the end tag of the page? Several methods are summarized as references
1 better reference to the JavaScript library (JsFile.js) using RegisterClientScriptInclude:
 
if (!Page.ClientScript.IsClientScriptIncludeRegistered("jsFileInclude")) 
Page.ClientScript.RegisterClientScriptInclude("jsFileInclude", "JsFile.js"); 

Add the JavaScript library reference at the beginning of the documentation for the viewstate data.
2 to insert 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 to the end of the document.
When the last parameter is set to true, the.net framework is automatically added to the start and end of the script tag (or merged with other generated JavaScript code based on the same script tag).
But we can also use the RegisterStartupScript method to load the reference to the JavaScript library at the end of the document. We write out the full 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); 

Related articles: