Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of bringing in jQuery into ASP.NET (or any other external JavaScript)

What is the difference between those three code samples here below? Is one better than the others and why?

1.Page.ClientScript.RegisterClientScriptInclude(typeof(demo), "jQuery", 
                                                ResolveUrl("~/js/jquery.js"));

2. 
<asp:ScriptManager runat="server">
    <Scripts>
      <asp:ScriptReference Path="~/jquery-1.2.6.min.js" />
      <asp:ScriptReference Path="~/jquery.blockUI.js" />
     </Scripts>
  </asp:ScriptManager>

3. <script type="text/javascript" src="/js/jquery.latest.js"></script> 

I've seen people using jQuery in their examples, and each one of them brings jQuery into ASP.NET in a different way. What is the best way?

like image 647
ra170 Avatar asked Apr 09 '09 06:04

ra170


3 Answers

The first one is

used on server side for adding client script

The second one is

used with managing of asp.net AJAX scripts.If jQuery detects an ASP.Net AJAX ScriptManager, it will use this to register the scripts instead of Page.ClientScript

The third one is

the plain way to register the jquery plugin

I typically prefer the last one over the second one, but I never use Ajax anyway, and the first it only needed when you want to add in script after a postback to the server is done

like image 100
TStamper Avatar answered Oct 22 '22 19:10

TStamper


I really don't like option 1 unless you are building a User Control.

I only use the ScriptManager if I'm going to be using the Microsoft AJAX Library on that page. Just putting that there add a lot of extra stuff your page has to download (check it out with Firebug sometime). If you have JavaScript in resource files the ScriptManager can also minify it for you. But that requires recompilation if you JavaScript changes.

I typically use option 3.

like image 34
Chris Brandsma Avatar answered Oct 22 '22 20:10

Chris Brandsma


It depends what you are trying to achieve. The first one adds the script tag to your page during rendering, from the server side. This can be useful for adding dynamically generated JavaScript and things like that.

The second option is only interesting if you're using ASP.NET AJAX for managing your JavaScript, because it registers a whole lot of other JavaScript on the page.

So if you want to keep everything clean and only plan on using jQuery, go with option 3.

like image 22
Graffen Avatar answered Oct 22 '22 19:10

Graffen