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.