Skip to content Skip to sidebar Skip to footer

Load Js Script After Another One Is Loaded

here's my code: //very big js file //lots of html stuff The problem is, that those are loa

Solution 1:

If you use jQuery, there is a very easy way to do this through getScript function. Just add the part of script that you need to be executed after the load and pass it as a parameter to the function.

$.getScript( "app.js" )
  .done(function( script, textStatus ) {
    console.log( textStatus );
    //your remaining code
  })
  .fail(function( jqxhr, settings, exception ) {
    //script fail warning if you want it
});

Solution 2:

Defer instructs the contents of the script tag to not execute until the page has loaded. So I would actually expect alert popup first and then app.js loaded.

Without defer the sripts should be synchronously loaded in the order you put them.

Solution 3:

You can achieve that by async-await

create a JavaScript function wrapping them both.

consttask1 = ()=>{
 // app.js content
}

consttask2 = ()=>{
 // alert(1);
}

asyncfunctionasyncCall(){
  awaittask1(); // then task2 want start until the task1 finishestask2();
};

asyncCall();

You can use async functions to execute one function after another one asynchronously

additional resources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

you can also solve the same problem using JavaScript Promises but I prefer async-await functions. they are less painful.

Post a Comment for "Load Js Script After Another One Is Loaded"