A clean way to enable jquery in ASP.Net MVC

How did you guys work with jQuery, include

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

in Asp.Net MVC when working with partial views / controls? Basically, I don’t want jquery to be included in the main page because I don’t use jquery in all of my views, but I also want a simple user control to be able to create jquery in the correct location ('head') order without creating duplicate jquery.

The best way would be to use ScriptManaager, but I don't want to rely on ASP.Net Ajax for this in my application. Is there a “lite” ScriptManager I could use that would also allow the new released intellisense for jquery?

I created a WebControl that provides this functionality, but I don't get the intellisense support for VS2008, which I really liked.

Hope this makes sense.

+5
source share
4 answers

If you use jQuery in a large percentage of your pages, I would just put it on the main page. It will only load once when it is cached in the browser and will have little effect on perf to render your page.

+13
source

You do not know how to do this, only with partial representations, although you can do this in stages with existing technology.

ContentPlaceHolder head. jQuery ContentPlaceHolder .

+3

Ahh trying to post this silence me because he is seen as part of the page ... but

<script src="<%=Url.Content("~/Content/js/jquery-1.2.3.min.js") %>" type="text/javascript"></script>
+1
source

You can always do this:

make easy util.js that is on every page, you can put various common things in it, plus this:

function loadJSInclude(scriptPath, callback)
{
    var scriptNode = document.createElement('SCRIPT');
    scriptNode.type = 'text/javascript';
    scriptNode.src = scriptPath;

    var headNode = document.getElementsByTagName('HEAD');
    if (headNode[0] != null)
        headNode[0].appendChild(scriptNode);

    if (callback != null)    
    {
        scriptNode.onreadystagechange = callback;            
        scriptNode.onload = callback;
    }
}

Then, in your opinion, just put:

<script type='text/javascript'>
    if(typeof(someJqueryObject) == "undefined")        
        loadJSInclude('jquery.js', doYourStuff);        
    else        
        doYourStuff();

    function doYourStuff()
    {
        // jQuery will be loaded now, so you can do your stuff here.
    }
</script>
0
source

All Articles