Oh my god. It's full of code!

Reliably injecting jQuery and jQuery UI with callback!

Hey all,
So this is kind of a cool thing. Sometimes you end up needing to inject jQuery in a page (like with advanced custom buttons in Salesforce) or in other cirumstances where you can write scripts, but you don’t have direct access to the source doc. Some of these times you want to include jQuery, along with jQuery UI and it’s CSS. Most of us know you can use the head.addScript function of javascript to inject the code, but how do you know when it’s loaded? How do you make sure you only load the UI library after the core library has loaded? Well worry no more, as I have an awesome javascript function here to reliably inject jQuery and the UI and then call a function of your choosing. Here ya go!

function loadJQuery(callback)
{
    try
    {
        if(typeof jQuery == "undefined" || typeof jQuery.ui == "undefined")
        {
            var maxLoadAttempts = 10;
            var jQueryLoadAttempts = 0;
            //We want to use jQuery as well as the UI elements, so first lets load the stylesheet by injecting it into the dom.
            var head= document.getElementsByTagName('head')[0];
            var v_css  = document.createElement('link');
            v_css.rel = 'stylesheet'
            v_css.type = 'text/css';
            v_css.href = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/redmond/jquery-ui.css';
            head.appendChild(v_css);

            //Okay, now we need the core jQuery library, lets fetch that and inject it into the dom as well
            var script= document.createElement('script');
            script.type= 'text/javascript';
            script.src= 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
            head.appendChild(script);
                    
            checkjQueryLoaded = setInterval(function()
            {             
                if(typeof jQuery != "undefined")
                {
                    //Okay, now we need the core jQuery UI library, lets fetch that and inject it into the dom as well
                    var script= document.createElement('script');
                    script.type= 'text/javascript';
                    script.src= 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js';
                    head.appendChild(script);
                    window.clearInterval(checkjQueryLoaded);
                }
                else if(maxLoadAttempts < jQueryLoadAttempts)
                {
                    window.clearInterval(checkjQueryLoaded);
                }
                jQueryLoadAttempts++;
            },300);
            
            jQueryLoadAttempts = 0;        
        
            checkLoaded = setInterval(function()
            {             
                if(typeof jQuery != "undefined" && typeof jQuery.ui != "undefined")
                {
                    window.clearInterval(checkLoaded);
                    callback(true);
                }
                else if(maxLoadAttempts < jQueryLoadAttempts)
                {
                    window.clearInterval(checkLoaded);
                    callback(false);
                }
                jQueryLoadAttempts++;
            },500);
        }
    }
    catch(exception)
    {
        callback(false);
    }
}

Then you can invoke it and have a callback like this

loadJQuery(function(loadSuccess){
    if(loadSuccess)
    {
	//Do your jQuery stuff here. Basically you can think of this as a replacement for your 
	//document.onReady code
        $(document.getElementsByTagName('body')[0]).append("<div id=infoNotice title='Success'>jQuery and jQuery UI loaded!</div>"); 
        $( "#infoNotice" ).dialog({ modal: true});  
    }
    else
    {
        alert('Couldn\'t load jQuery :(');    
    }
});

Have fun!

4 responses

  1. Hollan

    Awsome! Thanks a lot! Regarding this I found painless solution. I installed jQuerify from here https://chrome.google.com/webstore/detail/jquerify/gbmifchmngifmadobkcpijhhldeeelkc
    It injects jQuery 1.8 even in HTTPS pages with one click with no conflict to Prototype )))

    October 25, 2012 at 5:27 pm

    • Edit: I forgot which post this was. I thought this was my post on injecting jQuery in a salesforce custom button. Turns out this is just the javascript I use to do that. In that case, yeah, both solutions are viable. You can use this code in other situations where you can run javascript to import the libraries, which is handy for situations like in Salesforce when you can run JS, but don’t have access to jQuery so if you want it, you have to import it. Since it’s savable runnable code, it’s good for that kind of thing.

      Original comment: Glad it helped. Keep in mind that extension is only going to make it work for you on that page load I’m pretty sure, where as my approach will make it available to all users all the time. Kind of different use cases.

      October 25, 2012 at 5:31 pm

    • liam

      I am pretty sure you are referring to a chrome plugin, and not a coded solution to injecting jquery into a page. Completely unusable for a developer that is faced with injecting jquery and the UI into a webpage. It would be ridiculous for example, to ask all your users to download/install that chrome plugin for your page to work.. much less the other vast majority of users that (unfortunately) use IE

      Anyway with that said, Thanks for this great bit of code!! I had a usecase exactly like this and liked your approach better (given the embedded callback). Great work

      August 26, 2013 at 3:46 am

  2. Johne403

    Very well written article. It will be helpful to anyone who usess it, as well as yours truly cakebabeabad

    May 8, 2014 at 2:09 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s