3

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?

bretterer
  • 5,693
  • 5
  • 32
  • 53

4 Answers4

3

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...
    }
}
Kao Vang
  • 412
  • 2
  • 3
2

This one works in all browsers

function done(){ //on submit function
    alert($);
}

function load(){ //load jQuery if it isn't already
    window.onload = function(){
        if(window.jQuery === undefined){
            var src = 'https:' == location.protocol ? 'https':'http',
                script = document.createElement('script');
            script.onload = done;
            script.src = src+'://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
            document.getElementsByTagName('body')[0].appendChild(script);
        }else{
            done();
        }
    }
}

if(window.readyState){ //older microsoft browsers
    window.onreadystatechange = function(){
        if(this.readyState == 'complete' || this.readyState == 'loaded'){
            load();
        }
    }
}else{ //modern browsers
    load();
}
Adam Merrifield
  • 10,307
  • 4
  • 41
  • 58
  • The issue is I ( as the host of the javascript file that clients are including on there page, want to be incharge of adding jquery if it does not exist. I want them to be able to just add one js file to their site – bretterer Jun 23 '12 at 01:21
  • @bretterer I've updated it so it should work as expected now! put your script in the function done :] – Adam Merrifield Jun 23 '12 at 01:56
  • Yes sir it does: http://jsfiddle.net/SG9Ez/5/ you need it to run in the head not onload with jsfiddle (or else window.onload will never fire because it's already loaded..) – Adam Merrifield Jun 23 '12 at 02:02
0

You could check if window.jQuery returns true, if it doesn't then include the library. something like this.

window.onload = function () {
    if (!window.jQuery) {
        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);
    }
    //You had this in the code you posted so I left it there
    console.log($('title').html());
}
davidaam
  • 443
  • 1
  • 8
  • 17
-1

Question has been covered many times in SO

This thread represents lots of good perspectives. Click on "votes" tab for jquery tag, will see it in the highest votes list

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

EDIT: difference in scenarios is checking local vs CDN. Reverse for this situation

Community
  • 1
  • 1
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • This is not what I asked... I want my .js file that a client includes to take care of adding jquery if it is not available. I dont want to rely on the client to include both, my .js file as well as jquery – bretterer Jun 23 '12 at 01:58
  • they don't include both, second only gets included if first doesn't exist. document.write will assure that it isn't asynchronous since browser will then have to process the script tag before proceeding – charlietfl Jun 23 '12 at 02:02
  • Could you give a better example of how this works by letting my script that i provided include jquery if needed? – bretterer Jun 23 '12 at 02:27
  • quite simple, when browser reaches `document.write` it exectutes, next thing browser sees now is the script tag it just wrote, so it has to process it before anything else. Appending to another section of page doesn't assure you proper placement , so order of exection isn't assured. Your code would wrapped in ready event. Ther is a reason that the votes are very high on the thread and answers...read it thoroghly – charlietfl Jun 23 '12 at 02:40
  • That would work if I wanted to have the client do the document.write but i am writing something like google analytics where the client loads my script and i want my script to do the loading of jquery – bretterer Jun 23 '12 at 02:44
  • you put it in your script. don't understand the problem...unlless they are making an asynchronus call to get your script after page loads. You could also run a recursive setTimout checking for jQUery before code executes – charlietfl Jun 23 '12 at 04:40