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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With