Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save JoeyBurzynski/3944bba7befd6868d661414111abf87f to your computer and use it in GitHub Desktop.

Select an option

Save JoeyBurzynski/3944bba7befd6868d661414111abf87f to your computer and use it in GitHub Desktop.
How To Defer Execution Of Javascript In The Browser

TL;DR: Use window.addEventListener(...) (see final heading)

You may want to defer execution of javascript until the DOM has loaded. For example, the following will not work.

function respondToEvent() {
    ... 
}

// Bind event listener
document.getElementById("elementName").addEventListener("event", respondToEvent, false);

getElementById will return undefined because it will be called before elementName exists in the DOM. So you need to wrap the event binding code in a function and execute it after the DOM has loaded.

The <body onload="function()"> Method

This works, but it's obtrusive. If your script depends on a HTML attribute, adding and removing the script requires alteration of the HTML. The backbreaking labour required is unfathomable and who knows what could clash.

The Defer <script> Attribute

Set the defer attribute when including the script

<script src="trackContentEditableSize.js" defer="defer" type="text/javascript"></script>

Then simply execute in the global context of the external javascript file:

... // define functions

bindEventListeners();

This works in Chrome version 40.0.2214.111 (64-bit). However, it is not recommended by MDN

Setting window.onload

```javascript` window.onload = bindEventListeners;


The problem here is that this could overwrite a `window.onload` property set by another script,
thereby breaking that other script.

# Adding an Event Listener to `window`

```javascript
window.addEventListener("onload", bindEventListeners, false);

This is probably the best option.

The addEventListener method allows adding multiple event listeners, without overwriting anything. The listeners will be executed when the event fires, in the order added by successive calls to addEventListener.

Note

You cannot use removeEventListener to remove the following event listener.

window.addEveneListener("event", function () { 
    ... // lambda body
}, false);

// FAILS
window.removeEveneListener("event", function () { 
    ... // identical lambda body
}, false);

removeEventListener requires the same arguments as addEventListener, including the original function object. So the supplied callback must be a global function, or a variable to which the original lambda was assigned; e.g.

     var lambda = function() { 
         ... // lambda body 
     };
     window.addEvenetListener("event", lambda, false);
     window.removeEventListener("event", lambda, false); // <--- WORKS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment