Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Neatest' way of adding javascript to a page footer in asp.net

Whenever i want to add a javascript library programatically, say jquery for example, it generally involves making sure there is a placeholder at the footer of my page, then calling a codebehind method that will take a link to the src as a parameter and return an htmlgeneric control, which is then added to this placeholder.

Is this still the neatest way to do it, even with .net 4.0 out?

like image 486
maxp Avatar asked Feb 14 '10 14:02

maxp


1 Answers

I think a better way is to use the RegisterStartupScript method:
http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx

And even better in your case RegisterClientScriptInclude:
http://msdn.microsoft.com/en-us/library/kx145dw2.aspx

EDIT:
Here's a sample of RegisterClientScriptInclude:

if (!Page.ClientScript.IsClientScriptIncludeRegistered("myJsInclude"))
   Page.ClientScript.RegisterClientScriptInclude("myJsInclude", "myJsFile.js");

EDIT2:
Here's a sample of an include with RegisterStartupScript:

string jsBlock = "<script src='myJsFile.js'></script>";

if (!Page.ClientScript.IsStartupScriptRegistered("myJsInclude"))
   Page.ClientScript.RegisterStartupScript(typeof(string), "myJsInclude", jsBlock, false);

You should add things like language="text/javascript" to the script tag, but for readability I didn't add them.

like image 163
Zyphrax Avatar answered Sep 21 '22 01:09

Zyphrax