0

Surely obvious but wanna be sure after some surprises in IE.

I've some js code defined in a .js file (nothing surprising here...).

I'd like to know what's the best practice to use this code (raw js, no framework here).

  1. Is it valid to:

    • insert window.onload = foo; inside the .js file

    • define foo in the html (foo containing objects defined in the file).

  2. Is it still possible to define other window.onload in the html?

If not, what's the best practice? Thanks in advance.

3 Answers 3

1

A more fool-proof way would be to use

window.onload = function() { foo(); };

and that is because, if window.onload = foo, is reached before the Foo is declared (within the html document) it will be registered as window.onload = undefined; And nothing will happen.

wrapping foo in a closure, you are ensuring that when the page is loaded, it will try to find and call foo, which will by then be already declared

(The above scenario won't happen if window.onload is ran on dom ready or below the declaration of foo)

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for this, is it good practice to insert window.onload in external file?
If that is the event you are after and not for example the dom content loaded one. (window.onload is called when all the assets of the page have loaded, including images etc. Whereas DomContentLoaded when the html "dom-tree" of the page is ready). Then yes there is nothing wrong with it. Just keep in mind that if you want to add/qeue functions you will need to do something like this jsdo.it/Pantelis/kjwJ (since setting the .onload property overwrites the previous value)
1

It's possible to have window.onload = func; anywhere, but the last will overwrite all others. In case you might have more than one handler, attach the event using the proper syntax per browser.

1 Comment

It's also answered by the word anywhere - this also includes external JS file. The JavaScript "compiler" won't start compiling before all the code is available, so you don't have to worry about server load or delay - such thing will affect the whole JS load time, and for this there exists "lazy loading" of JS files - using such technique, one indeed lose the onload event.
0

.js code will be "injected" into the document and treated the same as if it were inline.

1 Comment

I know that, my question is more about delay when loading js file. You can't use code straight when defined in external file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.