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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With