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?

4 Answers 4

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...
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

would this go within the window.onload function?
His code is in a self executing function, but I don't see a reason why it wouldn't work inside window.onload().
Looks like i may have had a typo. Sorry about that.
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();
}

3 Comments

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 I've updated it so it should work as expected now! put your script in the function done :]
Yes sir it does: 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..)
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());
}

Comments

-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

6 Comments

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
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
Could you give a better example of how this works by letting my script that i provided include jquery if needed?
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
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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.