Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use IIFE or window onload to initialize?

Both of the following code snippets worked:

Using IIFE in js file:

(function initialize() {
  txtInput = document.getElementById('txtInput');
  txtResult = document.getElementById('txtResult');

  txtInput.value = "0";
  txtResult.value = "0";

}());

Calling initialize() on window load event in html file:

window.addEventListener('load', initialize, false);

Is one a better approach than other; in terms of performance or otherwise? As it stands right now, I am leaning more towards adding event listener to the window object, because it is more readable.

like image 315
GMalla Avatar asked Mar 20 '14 15:03

GMalla


2 Answers

It depends when you want the code to run. If you want the code to execute ASAP you can use an IIFE but there is really no point using an IIFE if you don't use it to protect your variables and/or not polluting the global scope.

(function initialize() {
    // do somthing
}());

or

// do somthing

will execute at the same point in time.

If you want to defer execution there are three points in time usually used by web devs. <script>s at bottom, DOMContentLoad and window.onload.

  • <script>s at bottom will execute after they are fetched from the server.
  • DOMContentLoaded basicly execute as soon as </html> has been read by the HTML parser.
  • very simplified window.onload executes after all CSS, <img>es and <script>s have been loaded.

Note that in reality, with attributes like async and defer on <script>s, this is more complex, . This is why there is a mountain of resource loaders available.

like image 177
anddoutoi Avatar answered Oct 03 '22 05:10

anddoutoi


Probably the result of each approach matters, not the performance. The first approach runs immediately while the second one waits until dom is ready. The end result is that in your first approach, you may end up getting undefined for both textInput and textResult, unless you place the script on the bottom of page.

like image 43
bingjie2680 Avatar answered Oct 03 '22 04:10

bingjie2680