Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load jQuery in IE and Chrome

I'm creating an external widget that uses jQuery and rather than have the user include it separately I'd like to check to see if it's loaded and load it dynamically if it's not.

Problem is I need to wait until it's loaded to execute the rest of the script, which requires event handlers that IE and FF/Chrome handle differently.

If I do this, it works fine in IE8:

<div id="test">
<p>This is a test.</p>
</div>

<script>
if (typeof jQuery == 'undefined') {
    s = document.createElement("script");
    s.src = "//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
    if (s.addEventListener) {
        s.addEventListener("load", runScript, false);
    } else if (s.readyState) {
        s.onreadystatechange = runScript;
    }

} else {
    runScript();
}

function runScript() {
    document.getElementsByTagName('head')[0].appendChild(s);
    $('#test').css('font-size', '50px');

}
</script>

But that doesn't work in Chrome. However if I append the script earlier, it works in Chrome but not IE:

<div id="test">
<p>This is a test.</p>
</div>

<script>
if (typeof jQuery == 'undefined') {
    s = document.createElement("script");
    s.src = "//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
    document.getElementsByTagName('head')[0].appendChild(s);
    if (s.addEventListener) {
        s.addEventListener("load", runScript, false);
    } else if (s.readyState) {
        s.onreadystatechange = runScript;
    }

} else {
    runScript();
}

function runScript() {

    $('#test').css('font-size', '50px');

}
</script>

Any ideas on how to dynamically load jQuery with event handlers that works both in IE and Chrome?

EDIT: Changed appendChild target from test to head.

like image 535
OrdinaryHuman Avatar asked Nov 13 '22 14:11

OrdinaryHuman


1 Answers

In the first code you are appending the script in the function you are calling when it is complete!

And what element is test?

document.getElementsByTagName('test')[0].appendChild(s);  <-- looking for element
<div id="test">  <-- test is an id

The code should look like

if (typeof jQuery == 'undefined') {
    var s = document.createElement("script");
    s.src = "//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
    if (s.addEventListener) {
        s.addEventListener("load", runScript, false);
    } else if (s.readyState) {
        s.onreadystatechange = runScript;
    }
    document.getElementsByTagName('head')[0].appendChild(s);
} else {
    runScript();
}

function runScript() {
    $('#test').css('font-size', '50px');
}

Running example: http://jsfiddle.net/5986T/

like image 177
epascarello Avatar answered Nov 15 '22 05:11

epascarello