views:

624

answers:

3

How have you guys handled working with jQuery includes

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

in Asp.Net MVC when working with partial views/view controls? Basically, I don't want to make the jquery include in the master page because I am not using jquery in all of my views, but I also want an easy way for a user control to be able to create the jquery include in the right location ('head') without creating duplicate jquery includes.

The best way would be to use a ScriptManaager, but I do not want to rely on ASP.Net Ajax for this in my application. Is there a 'lightweight' ScriptManager that I could use that would also allow the newly released intellisense for jquery?

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

Hope this makes sense.

A: 

You could always do this:

make a lightweight util.js that is in every page, in it you could put various common stuff, 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 view, just place:

<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>
FlySwat
but you wont get the nice intellisense with this
Cipher
+3  A: 

Not sure how to do this with only partial views though you could do it on a page-by-page basis with existing technology.

You could create a ContentPlaceHolder in your master page inside of the head tag. Than in your user controls just put the jQuery include in the ContentPlaceHolder content area of your pages.

Chad Moran
+12  A: 

If you use JQuery in a high percentage of your pages, I'd just put it in the master page. It's only going to be downloaded once at which point it's cached on the browser and will have negligible impact on perf for rendering your page.

Haacked