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.
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.
Share Improve this question edited Apr 15, 2017 at 13:00 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Oct 19, 2016 at 17:16 RubioliRubioli 7257 silver badges37 bronze badges 6- try imported.async = true – Priyesh Kumar Commented Oct 19, 2016 at 17:19
-
async
is not defined in your script.. Either define it or justimported.async = true;
– Rayon Commented Oct 19, 2016 at 17:21 - Possible duplicate of Create script tag with async attribute – Heretic Monkey 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 – Rubioli Commented Oct 19, 2016 at 17:24 -
@MikeMcCaughan Thats with
jQuery
and I look for a purejavascript
– Rubioli Commented Oct 19, 2016 at 17:24
2 Answers
Reset to default 5async
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/en-US/docs/Web/HTML/Element/script
I can not ment.. 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.