Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load external javascript file after onload()

I use this in the head tag:

<script src="js/lightbox.js"></script>

Is it possible to remove this off the header and load this file with onload()?

<body onload="...">...</body>

Note: This is not a function, it's an external js file with several functions.

Thanks!

like image 234
Roman Tisch Avatar asked Dec 08 '25 22:12

Roman Tisch


1 Answers

<script>
function loadJS(src, callback) {
    var s = document.createElement('script');
    s.src = src;
    s.async = true;
    s.onreadystatechange = s.onload = function() {
        var state = s.readyState;
        if (!callback.done && (!state || /loaded|complete/.test(state))) {
            callback.done = true;
            callback();
        }
    };
    document.getElementsByTagName('head')[0].appendChild(s);
}
loadJS('/script/script.js', function() { 
    // put your code here to run after script is loaded
});
</script>

I still think its better to load in jQuery and use $.getScript instead as you have lots of goodies there.

Can call this on body load

like image 55
Vinay Pratap Singh Bhadauria Avatar answered Dec 11 '25 11:12

Vinay Pratap Singh Bhadauria



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!