Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add ASYNC to <script> tag on when running document.head

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.

like image 287
Rubioli Avatar asked Nov 14 '25 22:11

Rubioli


1 Answers

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

like image 84
Priyesh Kumar Avatar answered Nov 17 '25 20:11

Priyesh Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!