Try the following code in your browser's console:
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://code.jquery.com/jquery-2.1.1.min.js';
script.async = true;
document.body.appendChild(script);
console.log($);
Then wait a few seconds and do this again:
console.log($);
So it takes a while for jQuery to load. I tried this suggestion, which seems to be the consensus of all related questions:
+function loadScript(url, callback)
{
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}("http://code.jquery.com/jquery-1.7.1.min.js", function(){console.log($);});
And once again it doesn't work ...
The first
console.log($)
should give the correct result. What can I do to execute a function as soon as jQuery has loaded and executed?
(Background: I'm writing a Chrome extension to fix formatting on a page that doesn't use jQuery.)