Claudio Ferraro
Claudio Ferraro

Reputation: 4721

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?

Upvotes: 3

Views: 255

Answers (3)

ChrisThompson
ChrisThompson

Reputation: 2008

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." );
});

Upvotes: 2

dc5
dc5

Reputation: 12431

You could rework your logic to trigger off the load event after appending the script tag to your page.

see: How to check if an asynchronously loaded script has finished loading in javascript

Since you are using JQuery, you could leverage JQuery.getScript

Upvotes: 1

Iswanto San
Iswanto San

Reputation: 18569

Use $(window).load(); instead $(document).ready(). See here for more explanations.

Upvotes: 1

Related Questions