Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How load a javascript file dynamically? [duplicate]

I have a js file that I want to load it dynamically in a web page using JavaScript. I want to load the file after the web page has been loaded.

Any help is welcome.

like image 722
Red Diesel Avatar asked Jul 19 '26 01:07

Red Diesel


2 Answers

You can do this with pure javascript or jQuery, here is the two ways (I prefer the jQuery way):

JavaScript

var h = document.getElementsByTagName('head')[0];
var s = document.createElement('script');
s.src = 'http://url.to/your/script.js';
h.appendChild(s);

jQuery

$.getScript('http://url.to/your/script.js');
like image 83
ifm Avatar answered Jul 21 '26 13:07

ifm


window.onload = function () {
    var head = document.getElementsByTagName('head').item(0);
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', 'some.js');
    head.appendChild(script);
}
like image 32
bagonyi Avatar answered Jul 21 '26 15:07

bagonyi



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!