2

We am loading a script dynamically using the following code:

  var script = document.createElement('script');
  script.type = 'text/javascript'
  script.onload = () => {
    console.log("script", window.myScript);
  };
  script.onerror = console.log;
  script.src = 'https://example.com/my_script.js';
  document.head.appendChild(script);

the script contains code like:

window.myScript = function(){ 
  // lots of code
  return 'library'; 
}();

Most of the time this works as expected and window.myScript exists when the script.onload is triggered. However in some rare occasions script.onload is triggered, but window.myScript is undefined;

I was able to reproduce a similar case by changing the script to:

window.myScript = function(){ 
  throw 'error';
  return 'library'; 
}();

However in this case there should be an additional error which we are not seeing in our logs (we log all errors using window.onerror);

Are there any other reasons why this can happen? We have seen this happen on Chrome 86 and Edge 86.

Or Assayag
  • 5,662
  • 13
  • 57
  • 93
Ostap Maliuvanchuk
  • 1,125
  • 2
  • 12
  • 32

1 Answers1

1

Your addition to document, does not mean that the window object has fully loaded. Adding the script to the document means that it will load once the DOM is ready, but by having DOM ready, does not mean that the window has fully loaded. There can be assets to load yet. I assume that, although rare, there is a case that your function exists in the DOM, but has not loaded on the window object.

Check out this interesting SO question on the topic.

One suggestion would be to add an EventListener on window loading, and then set your script loading in there:

window.addEventListener('load', (event) => {
  // Your loading code here
  var script = document.createElement('script');
  script.type = 'text/javascript'
  script.onload = () => {
    console.log("script", window.myScript);
  };
  script.onerror = console.log;
  script.src = 'https://example.com/my_script.js';
  document.head.appendChild(script);
});
Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54
  • Thank you for the answer, I am not sure that this is our issue as it happens sometimes (~20 seconds) after the page is loaded, but if there are no more answers in some time I will accept it. – Ostap Maliuvanchuk Dec 03 '20 at 09:21