bryane92
bryane92

Reputation: 31

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>

Upvotes: 0

Views: 281

Answers (2)

Meowster
Meowster

Reputation: 657

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.

Upvotes: 0

whoshotdk
whoshotdk

Reputation: 286

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>

Upvotes: 3

Related Questions