flyersun
flyersun

Reputation: 917

Using javascript to create Jquery link

We have a dynamic adbanner which is loaded onto websites via Google Double Click.

We use some Jquery in the code so as part of the set up we check if a website is running Jquery and if not we use Javascript to add a link to our Jquery file.

This is being done fine however I'm still getting an error "Uncaught ReferenceError: jQuery is not defined" I'd assume this is due to the order things are loading in but I'm not sure how to get around the issue. Everything works fine if you refresh the page the problem only seems to happen on first load.

Also if I open a new browser window and load the page a second time everything works fine.

Here's the code we are using to add the script tags to the head:

if(!window.jQuery)
 {

    var fm_j = document.createElement('script'); fm_j.type = 'text/javascript';
    fm_j.src = 'js/jquery-1.8.3.min.js';
    document.getElementsByTagName('head')[0].appendChild(fm_j);
 }

Upvotes: 0

Views: 85

Answers (2)

colestrode
colestrode

Reputation: 10658

This is a timing issue. When you load scripts dynamically like that, they are loaded asynchronously and don't block further execution of javascript on the page. This means that jQuery may not be loaded by the time your jQuery specific code is being run.

When you refresh, js/jquery-1.8.3.min.js has probably been cached and so will load faster, so you don't see errors.

The solution is to wrap your javascript into a function that is called once jQuery has loaded using a load event handler. Here's an example I adapted from this tutorial.

working example.

function getScript(success) {

    var fm_j = document.createElement('script'); 
        fm_j.type = 'text/javascript';
        fm_j.src = 'js/jquery-1.8.3.min.js',
        done = false;

    // Attach handlers for all browsers
    fm_j.onload = fm_j.onreadystatechange = function () {
        if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {

            done = true;
            // callback function provided as param
            success();
        };
    };

    document.getElementsByTagName('head')[0].appendChild(fm_j);
};

if(!window.jQuery) {
    getScript(doSomething);
} else {
    doSomething();
}

Also, as several commentors pointed out, many sites place banner ads inside iframes to keep the ads from "polluting" your page with their libraries.

Upvotes: 6

Akki619
Akki619

Reputation: 2432

iFrame could have been a better way to go @flyersun

It's simple and easy and effective, see here

http://support.microsoft.com/kb/272246

Upvotes: 0

Related Questions