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?

4

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.