JavaScript

When to run your code

When is the right time to run your JavaScript? When the page has loaded? When the document is ready? You may face this challenge and the solution sometimes is not so simple.

The Browse inconsistently offers solution to this problem.

Run on Load.

Running your code when the load event is triggered is the easiest solution. You can make use of the onload method available in the window object.

window.onload = function () {
    console.log("Everything is loaded, now I run");
}

When everything is loaded on the page is loaded, your code will run. I mean everything. This works well if you have very few or no assets on your page. But imagine a gallery page that contains large images. Your code will have to wait for all the images to be loaded before it runs. If you are setting up click events in your code, the user will notice the buttons not working before the page completes.

By using the onload() method, you face a problem if you want to add multiple functions to run when the page is loaded. One dirty trick to fix this is to check if the onload is a function then cache it and append the other function.

if (typeof window.onload === "function"){
    var tmp = window.onload;
    window.onload = function () {
        tmp();
        myFunction();
    };
}else {
    window.onload = myFunction;
}

Yeah I know, dirty. A better way to do the same task, is to use the addEventListener method.

window.addEventListener("load",myFunction1,false);
window.addEventListener("load",myFunction2,false);
window.addEventListener("load",...,false);

Each of these functions will run when the page is loaded. They will run in the order they were added.

Note: Previous versions of IE use the attachEvent() method instead. So make sure you check if the method exists first before calling it.

Run on DOM ready

jQuery is a blessing, it makes it very easy to trigger code when the DOM is ready. Every browser has their own way of implementing it. The simplest the support it uses the DOMContentLoaded event:

window.addEventListener("DOMContentLoaded",myFunction1,false);

The DOM is ready when the browser finnished downloaded all the HTML and parsed the code. Not all the files has been downloaded though. This is a good time to run your code usually since the event fires before all the assests finish download. In most cases, as soon as the page appear, the user can interact with it.

If you are interested to see how jQuery does it, here it is on github

Run whenever

There are cases where your code doesn't need to wait for the page to be ready to run. All it needs is for the DOM elements it neeeds to modifify to be present to run. Your code will run asynchronously.

<div class="newsletter">
    <!-- Validate email and make ajax request to subscribe the user -->
</div>

Both onload or domready can be used to add the functionality to the newsletter. But another method is to run as soon as the div is present:

<div class="newsletter">
    <!-- Validate email and make ajax request to subscribe the user -->
</div>
<script>initializeNewsletter();</script>

Easy right? you just have to make sure your function is defined before you run the code. I know it is usually recommended to separate your JavaScript from the view, but it is only the first in making your code modular, I will show you in a future tutorial.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only