Reputation: 3826
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?
Upvotes: 0
Views: 795
Reputation: 2841
If you are using jQuery, then you could use the .getScript
function.
jQuery.getScript("https://xxxx/jquery-3.2.1.js");
Upvotes: 1
Reputation: 2841
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);
Upvotes: 0