4

I'm trying to inject a JavaScript file into <head></head>. The JavaScript file is async, and I want to add it to the script tag when injecting.

This is what I have so far:

var imported = document.createElement('script');
imported.src = 'http://domain/js/my.js';
imported.setAttribute("type", "text/javascript");
imported.async = async;
document.head.appendChild(imported);

This injects the JavaScript file, but I get error on line imported.async = async;:

uncaught ReferenceError: async is not defined

And async is not added to the tag.

How can I add async into that injected JavaScript file?

PS: I'm not looking for a jQuery answer, only pure JavaScript.

6
  • try imported.async = true Commented Oct 19, 2016 at 17:19
  • async is not defined in your script.. Either define it or just imported.async = true; Commented Oct 19, 2016 at 17:21
  • Possible duplicate of Create script tag with async attribute Commented Oct 19, 2016 at 17:22
  • @PriyeshKumar Thanks, imported.async = true is correct. Add it as a answer and I can check it as correct Commented Oct 19, 2016 at 17:24
  • @MikeMcCaughan Thats with jQuery and I look for a pure javascript Commented Oct 19, 2016 at 17:24

2 Answers 2

5

async variable is not defined and so imported.async = async; will throw error.

You can do var async = true; or false and then imported.async = async;

OR

imported.async = true;

Note that async attribute should be boolean.

Read docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

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

Comments

0

I can not comment.. because I don't have the rep. But I wanted to add to the accepted answer, that you could also have done:

imported.async = !!async;

this would asign false if the value is false or if async is undefined and true only if defined and initialized on true.

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.