Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How start executing code when the script loading is completed

I have this code:

$(document).ready(function() {
    window.addEventListener('DOMContentLoaded', function() {
    var s = d.createElement('script');
    s.async = false;
    s.src = 'file.js';
    s.id = 'script';
    d.body.appendChild(s);
    });
});

$(window).load(function() {
    workwithvariablesInfilejs();
});

It seems that the document.ready fires first and window.load fires after. But if try to access the variables of the file.js I have troubles because it seems that the file.js script loads after window.load. How can I wait until the file.js is loaded ? Or is there a better way to organize this code?

like image 250
Claudio Ferraro Avatar asked Jul 07 '26 22:07

Claudio Ferraro


1 Answers

you could use the getscript method: http://api.jquery.com/jQuery.getScript/ then make the "workwithvariablesInfilejs()" call inside the ".done" callback.

$.getScript("file.js")
.done(function(script, textStatus) {
  console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
  $( "div.log" ).text( "Triggered ajaxError handler." );
});
like image 107
ChrisThompson Avatar answered Jul 10 '26 12:07

ChrisThompson



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!