-1

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 ... enter image description here 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.)

Simon Kuang
  • 3,870
  • 4
  • 27
  • 53

1 Answers1

1
function loadScript(url, callback){
    var foo1 = document.createElement('script');
    foo1.type = 'text/javascript';
    foo1.setAttribute('src', url);

    foo1.onreadystatechange = callback;
    foo1.onload = callback;

    var head = document.getElementsByTagName('head')[0];
    head.appendChild(foo1, head);
}
loadScript(('https:' == document.location.protocol ? 'https://' : 'http://') +'code.jquery.com/jquery-1.11.0.min.js', function(){
    console.log($);
});
alessandrio
  • 4,282
  • 2
  • 29
  • 40