ra170
ra170

Reputation: 3683

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?

Upvotes: 6

Views: 306

Answers (4)

Graffen
Graffen

Reputation: 213

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.

Upvotes: 1

TStamper
TStamper

Reputation: 30364

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

Upvotes: 2

Chris Brandsma
Chris Brandsma

Reputation: 11736

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.

Upvotes: 1

Al W
Al W

Reputation: 7713

Method #2 works well if I want the js to be included for a certain usercontrol, but not on every page. The scriptmanager also makes sure I don't have duplicate script references. If you want the js included on every page (as jquery will almost always be) then method #3 is cleanest.

Upvotes: 0

Related Questions