here's my code:
<script src='app.js' defer></script> //very big js file
//lots of html stuff
<script> alert(1);</script>
The problem is, that those are loaded asynchronously. Is there a way to wait for the second script until the first one is loaded?
here's my code:
<script src='app.js' defer></script> //very big js file
//lots of html stuff
<script> alert(1);</script>
The problem is, that those are loaded asynchronously. Is there a way to wait for the second script until the first one is loaded?
Share Improve this question edited Oct 3, 2018 at 13:00 Zbyszek Kisły asked Oct 3, 2018 at 12:57 Zbyszek KisłyZbyszek Kisły 2,2386 gold badges29 silver badges53 bronze badges 1 |3 Answers
Reset to default 7If 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
});
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.
You can achieve that by async-await
create a JavaScript function wrapping them both.
const task1 = ()=>{
// app.js content
}
const task2 = ()=>{
// alert(1);
}
async function asyncCall(){
await task1(); // then task2 want start until the task1 finishes
task2();
};
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.
defer
. – Niet the Dark Absol Commented Oct 3, 2018 at 13:00