最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add ASYNC to <script> tag on when running document.head - Stack Overflow

programmeradmin1浏览0评论

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 just imported.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 pure javascript – Rubioli Commented Oct 19, 2016 at 17:24
 |  Show 1 more ment

2 Answers 2

Reset to default 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/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.

发布评论

评论列表(0)

  1. 暂无评论