skip to Main Content

In my html I have 2 script tags:

<script src="first.js"></script> 
<script src="second.js"></script>

first.js is a large library file, and would make funcFromFirstJs available. I want to call this func when it becomes ready. I currently use this recursive strategy like so:

// second.js

function callIfReady() {
  if (typeof funcFromFirstJs === 'function') {
    funcFromFirstJs();
  } else {
    // wait for a few seconds and callIfReady() again
  }
}

Is there a better way?
I am aware of window event 'load' which is supposed to fire when all sources in html including images have finished loading completely. I’m also aware of document event DOMContentLoaded which happens when tags are loaded, but may happen before their content completely finishes loading.
Because first.js is a library file, so I also do not want to add my js code at the bottom of first.js.
So specifically, I just want to wait for first.js to finish loading completely, then run this code in second.js. I certainly do not care about the loading progress of other things like images or other script tags; this is why I do not want to use window event: load.

2

Answers


  1. it comes ‘undefined’ when you called.?

    Login or Signup to reply.
  2. If you were my colleague, I’d firstly ask you why you decided to use such approach at all and why you don’t use any bundler which could effectively merge all your scripts into a single file, as well as minimise its size via tree-shaking.

    However, if you still want to achieve the behaviour described in your question, one of the approaches you may use is: to add the first script from the second one and wait until ‘onload’ event fires. Like this:

    // second.js
    
    function callWhenReady() {
        funcFromFirstJs(); //everything you need from the first.js
    }
    
    const s = document.createElement('script'); // create script element
    document.body.appendChild(s); // append it to the DOM
    s.onload = callWhenReady; // execute when script loaded
    s.src = 'https://...path/to/first.js'; // set path to script
    

    With this slightly tricky solution you should be able to execute anything you need from the first.js script in the function `callWhenReady’;

    P.S.
    Of course you should remove ` from the HTML in this case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search