最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Load JS script after another one is loaded - Stack Overflow

programmeradmin11浏览0评论

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
  • 5 If order of execution is important, then you shouldn't be using defer. – Niet the Dark Absol Commented Oct 3, 2018 at 13:00
Add a comment  | 

3 Answers 3

Reset to default 7

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

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.

发布评论

评论列表(0)

  1. 暂无评论