1

I'm looking for code that allows me to use JavaScript to load another JavaScript file NON-asynchronously. I tried this:

var script=document.createElement('script');
script.setAttribute("type","text/javascript");
script.setAttribute("src", "jquery.min.js");
document.getElementsByTagName("head")[0].appendChild(script);

$("div.whatever").css("color","red");

But that doesn't work. It inserts the script node okay, but it continues to run the rest of the script before jQuery loads. This ends up failing because the jQuery code tries to run when $ isn't defined by jQuery yet.

Is there a way to load that script non-async using native JS?

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370

2 Answers2

3

You can either use the <script> nodes .onload event handler, to continue/execute any code which should be executed after the script was loaded, like

script.onload = function() {
    // continune here
};

or you can try to set the async flag to false

script.setAttribute("async", false);

While the former solution virtually works in any browser available, the latter one might be not supported by old'ish browsers.

jAndy
  • 231,737
  • 57
  • 305
  • 359
0

Instead of loading synchronously, a slightly better idea might be to use onload:

script.onload = function() {
  // $ is defined now
};

// append it only now to make sure it does not load before setting onload
document.getElementsByTagName("head")[0].appendChild(script);
pimvdb
  • 151,816
  • 78
  • 307
  • 352