I would like to know, how to run something after the jQuery load? Does the jQuery got an ‘I’m ready’ event?
first in my getls.js
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://example.com/setls.js';
document.getElementsByTagName('body')[0].appendChild(script);
and then in the setls.js
if (typeof jQuery == 'undefined') {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js';
document.getElementsByTagName('body')[0].appendChild(script);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://example.com/ls.js';
document.getElementsByTagName('body')[0].appendChild(script);
ls.js
$("body").css("background-color", "green");
But the ls.js loads faster than jquery and tells me Uncaught ReferenceError: $ is not defined. How can i handle this event? Thanks for the help.
Edit: This is because this script will be something like the google analytics, you know. To let the user use just one line of script and load getls.js in his code, will makes him happy (Oh cool, its just 4 lines? Needy). But i also have to check jQuery because i will use jQuery later, and if already got it, I can’t load it again. After this I would like to use it.
So it’s not about document.ready event, the document was ready before I started to load the jQuery.
You want to load both scripts dynamically. You have two options :
onloadon the script you are injecting. It is supported on all major browsers, but test it on IE as it was not working a couple of years ago on IE. This is a clean solution.typeof(window.jQuery). When it is defined, jQuery should be loaded.