Search code examples
javascriptjquerydynamic-loading

Dynamically loading jQuery from hosted javascript file if not available on page


The idea of what I'm trying to do is allow a client to add a script that I host onto their website. I want to be able to use jQuery in my script but can not say for sure that it will always be available. Here is what I have code wise. This is the full file of my hosted javascript page so far and I can not get it to work. The $('title').html part is just so I can see if it works

I want the script that I am hosting to take care of including jQuery on the clients website. I do not want the client to have to include jQuery in addition to my script

window.onload = function () {
    if (typeof jQuery == 'undefined') {
        var jq = document.createElement('script'); 
            jq.type = 'text/javascript'; 
            jq.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
        var sc = document.getElementsByTagName('script')[0];
            sc.parentNode.insertBefore(jq, sc);
    } 

    console.log($('title').html());

}

This javascript file is loacated on my server and my client would include this file in much of the same way that you would for google analytics.

This is the only thing that I want my client to have to include. Pulled basically the same as google analytics

<script type="text/javascript">
    var _waq = _gaq || [];
        _waq.push(['PARAM1', 'PARAM2']);

    (function() {
        var wa = document.createElement('script'); 
            wa.type = 'text/javascript'; 
            wa.async = true;
            wa.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'PATH/TO/SCRIPT/wa.js';
        var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(wa, s);
    })();
</script> 

When I run the page I get an error saying Uncaught ReferenceError: $ is not defined however if I then right after the page loads, i type in $('title').html(); I get the title returned in the console.

Im sure this has something to do with timing of when the console.log in the script is running and has not let jQuery fully load yet. My question is how am I able to create a javascript page that a client can add that dynamically loads jquery if it is not available, and have it loaded before any of the other stuff on the script runs?


Solution

  • My coworker just had to solve the same issue. Ripped from his code, variables changed to reflect your code.

    if(jq.readyState) {
        // For old versions of IE
        jq.onreadystatechange = function() {
            if(this.readyState == 'complete' || this.readyState == 'loaded') {
                // do something...
            }
        }
    } else {
        // Other browsers
        jq.onload = function() {
            // do something...
        }
    }