0

I have a JS question, which is either tricky or stupid, not sure.

So, let's say I need to execute a function when an external JS script on the page finishes loading completely, because otherwise i'll get an error.

case 1:

var s = document.createElement('script');
s.src = "http://somedomain/somescript.js"

function foo() {
doSomething;
}

s.onload = foo;

in this case the function itself assigned to onload, and should run when the script finishes loading.

case 2:

s.onload = foo();

In this case, according to What is the different between window.onload = init(); and window.onload = init;, the return result of the function is assigned when the load finishes, so, the function can start executing in the beginning of the load, and not when the element finishes loading, depends on the browser.

case 3:

s.onload = function() {
doSomething;
}

This is the tricky part. I think that this syntax should execute like case 2, but i can't substantiate this. Am I just defining the function or both defining and executing it at the same time?

Pavel_K
  • 10,748
  • 13
  • 73
  • 186
  • `function() {...}` just defines an anonymous function. You would need `(function() {...})()` to immediately-invoke it. – Niet the Dark Absol Aug 13 '17 at 08:35
  • Hi, there is a function in the script that loads that i need to use, so i need to wait for the script to completely load before i address this function. The question is, whether this syntax `s.onload = function() { doSomething(); }` will actually wait until the script is **completely** loaded, because if it will start executing when the origin script is not loaded there will be an error. – Alexander Knurenko Aug 13 '17 at 10:37
  • @NiettheDarkAbsol where can i find the sourcecode to window.onload assignment and execution? – jmunsch Aug 13 '17 at 11:35
  • Possible duplicate of [Trying to fire the onload event on script tag](https://stackoverflow.com/questions/16230886/trying-to-fire-the-onload-event-on-script-tag) – jmunsch Aug 13 '17 at 11:37

2 Answers2

-1

use this :

window.onload = function(){

    //running your function

}
Luki Centuri
  • 185
  • 1
  • 6
  • Hi, thanks, but this is not what i asked. First of all I need to wait for script to load, not thew whole window, and second, this implementation gives an error, so i'm trying to find out whether case 3 is like case 2 or case 1. – Alexander Knurenko Aug 13 '17 at 09:27
-2

Try using addEventListener:

s.addEventListener("load", foo());

For more information reference w3schools: addEventListener

yoav sarfaty
  • 43
  • 1
  • 1
  • 8