I am trying to reference an external JS file asynchronously in document.read() event in application.
What am I currently doing to achieve this?
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'https://xxxx/jquery-3.2.1.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
My Question:
Is there a better way to achieve the same thing with less lines of code using any other methods?
如果您使用 jQuery,那么您可以使用.getScript
函数。
jQuery.getScript("https://xxxx/jquery-3.2.1.js");
I think the way you are doing it now is a good way of doing it. But if you want fewer lines of code and/or want the html you are adding to be more visible, you could do this.
var t = createElement("div");
t.innerHTML = '<script type="text/javascript" async src="https://xxxx/jquery-3.2.1.js"></script>';
var x = document.querySelector("script");
x.parentNode.insertBefore(t.childNodes, x);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.