user6589814 user6589814 - 1 month ago 5
Javascript Question

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

Im trying to inject a

js
file into
<head></head>
. The
js
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
js
file, but I get error on this 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
js
file.

PS: Im not looking for a
jQuery
answer, only pure
javascript

Answer

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

Comments