When you are writing JavaScript that interacts with elements on your page, you always need to ensure that the elements have loaded first. Not doing so could be difference between an application that works and one that throws an error because, at the time your code ran, some element your code was looking for didn't exist. While this seems straightforward, there are various shades of the correct solution you can take.
In this short tutorial, I will cover three ways to ensure your code always runs after your document has loaded, but before we get there, let's look at the three stages of a page getting loaded.
Initially, when a request is made to load a web page, there is nothing there. Nothing has been downloaded. There is simply nothingness.
Notice that, at this point, you may see some of the text that makes up your content but none of the images or styles that are located outside of your document will show up. That will only happen later.
While external images and style sheets won't get loaded, both inline and external scripts will though.
It is this stage that all of us would consider a page as having been fully loaded.
In the next three sections, you will take what you've learned here and see how it applies to ensuring our code runs after the content has loaded.
Using our page load examples, your script would load just after Step 2:
This approach gets the job done, and if you have control over where your script lives on a page, there is nothing wrong with doing this.
This corresponds to Stage 3 from our earlier list. In general, I would avoid using this event unless your script requires everything being loaded first. For example, if you need to wait for a full layout pass to be done after all of the content gets loaded, the load event is what you should listen for. For everything else, I would use the event you'll see next.
Below is a small example of how you can do that:
With this event, you gain the advantage of placing your script anywhere in your document while still making sure it runs only after your DOM has loaded without having to wait for every single thing in your page having loaded first.
The nice thing is that any scripts that you may rely on will have run by the time this event gets fired. Inline and external scripts will get run, so elements created dynamically can be accessed.
Instead of giving you my reasons for this ordering, try running the following example instead:
While the example is a little contrived, it gives you a good indication of why I lean towards the DOMContentLoaded event unless I absolutely need to wait for everything to get loaded. There is often no need to have your scripts wait until everything gets loaded, so there is no point in letting your visitors waste time unnecessarily!
In this short tutorial, I will cover three ways to ensure your code always runs after your document has loaded, but before we get there, let's look at the three stages of a page getting loaded.
NOTE
This article will touch upon JavaScript events and event handler. If you are not familiar with them, please look into my earlier JavaScript Events tutorial.
This article will touch upon JavaScript events and event handler. If you are not familiar with them, please look into my earlier JavaScript Events tutorial.
Anatomy of a Page Load
Before looking at how to ensure our scripts run after your content gets loaded, let's take a step back and look at the stages of a page getting loaded first...through the eyes of a browser and you.Step 1: First Contact
When you are first loading a web page, here is what you both see:Step 2: DOM Content Loaded
A few moments later, the markup of your document will get loaded with the initial DOM (aka the various HTML objects that make up your document) ready:While external images and style sheets won't get loaded, both inline and external scripts will though.
Step 3: Everyhing is Loaded
The final stage is where your document is fully loaded with all external content such as images, style sheets, scripts, etc. making an appearance:In the next three sections, you will take what you've learned here and see how it applies to ensuring our code runs after the content has loaded.
Placing Your Code at the End
The easiest way to ensure that your document has adequately loaded is to place any scripts that interact with elements on the page towards the bottom of your document just above the closing body tag:- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- </head>
- <body>
- .
- .
- .
- <script src="myScript.js"></script>
- </body>
- </html>
Using our page load examples, your script would load just after Step 2:
Waiting till Everything Loads
A safe choice for running your script is waiting until everything loads. You can do that by listening for the load event:- <script>
- this.addEventListener("load", doStuff, true);
- function doStuff(e)
- {
- // place code here
- }
- </script>
Waiting for the DOM to Load
There will be times when you won't have control over where your script will be placed in your document, but you may still want your code to start running after the DOM is loaded as opposed to when everything is loaded. Fortunately, you can still emulate this behavior by listening to the DOMContentLoaded event.Below is a small example of how you can do that:
- <script>
- this.addEventListener("DOMContentLoaded", doStuff, true);
- function doStuff(e)
- {
- // place code here
- }
- </script>
The nice thing is that any scripts that you may rely on will have run by the time this event gets fired. Inline and external scripts will get run, so elements created dynamically can be accessed.
Conclusion
There you have it - three ways of ensuring your code runs safely without running into issues where your document hasn't loaded. If I had to rank the approaches, my personal preference is to listen for the DOMContentLoaded event first, place the script towards the bottom of the page next, and listen to the load event last.Instead of giving you my reasons for this ordering, try running the following example instead:
[ come on, you know you want to try it out yourself ]
Notice that the DOMContentLoaded event gets fired much earlier than the load event which waits for every single image to get loaded first.While the example is a little contrived, it gives you a good indication of why I lean towards the DOMContentLoaded event unless I absolutely need to wait for everything to get loaded. There is often no need to have your scripts wait until everything gets loaded, so there is no point in letting your visitors waste time unnecessarily!
0 comments
একটি মন্তব্য পোস্ট করুন