简体   繁体   中英

How to ensure Javascript file loads after event listener triggers?

I currently have an event listener that listens for something to trigger. I would like for the event to trigger before trying to load the js file. Right now the JavaScript is loading and then the api is ready. How can I get the EventListener to fully complete before the main.js file loads?

    <head>
        <title>Default</title>

        <script>document.addEventListener(apikey,function () {
            console.log("ready");
            });
        </script>
        <script src="./js/main.js"></script>
        <script>console.log("js loaded")</script>       
       
    </head>

Remove the script tag to main.js.

Inside your event listener function, create and add a script tag to the document:

Your code should look like:

<head>
  <title>Default</title>
  <script>
    document.addEventListener(apikey, function() {
      const myscript = document.createElement('script');
      myscript.src = './js/main.js';
      document.body.appendChild(myscript);
    });
  </script>
  <script>
    console.log("js loaded")
  </script>
</head>

You can do something like this:

<head>
    <link href="./js/main.js" rel="preload" as="script">

    <script>
        async function runScript(src) {
            let script = document.createElement('script');
            script.src = src;
            document.head.append(script);
        }
    
        document.addEventListener(apikey, () => {
            runScript('./js/main.js');
        });
    </script>
</head>

The advantage of this approach is that the script will start loading immediately, regardless of the event. And it can be called from the event without wasting extra time.

Browser compatibility: preload .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM