How To Make Javascript Execute After Page Load

An important part of working with JavaScript is ensuring that yourcode runs at the right time. Things aren"t as simple as putting yourcode at the bottom of your page và expecting everything khổng lồ work once yourpage has loaded. Every now & then, you may have to lớn add some extra codeto lớn ensure your code doesn"t run before the page is ready. Sometimes, youmay even have to put your code at the top of your page...lượt thích an animal!

There are many factorsthat affect what the "right time" really is to run your code, và inthis tutorial, we"re going khổng lồ look at those factors and narrow down whatyou should bởi to a handful of guidelines.

Bạn đang xem: How to make javascript execute after page load



OMG! A JavaScript Book Written by!!

To kiông chồng your JavaScript skills into lớn outer space, everything you see here và more (with all its casual clarity!) is available in both paperbachồng và digital editions.


The Things That Happen During Page Load

Let"s start at the very beginning. You cliông chồng on a liên kết or press Enterafter typing in a URL &, if the stars are aligned properly, your pageloads. All of that seems pretty simple & takes up a very tiny sliverof time lớn complete from beginning lớn end:


In that short period of time between you wanting lớn load a page andyour page loading, many relevant và interesting stuff happen that youneed lớn know more about. One example of a relevant and interesting stuffthat happens is that any code specified on the page will run. When exactly the code runsdepends on a combination of the following things that all come alive sầu atsome point while your page is getting loaded:

The DOMContentLoaded sự kiện The load EventThe async attribute for script elementsThe defer attribute for script elementsThe location your scripts live in the DOM

Don"t worry if you don"t know what these things are. You"ll learn (orre-learn) what all of these things bởi vì và how they impact when your coderunsreally soon. Before we get there, though, let"s take a quichồng detour andlook at the three stages of a page load.

Stage Numero Uno

The first stage is when your browser is about tostart loading a new page:


At this stage, there isn"t anything interesting going on. A requesthas been made to lớn load a page, but nothing has been downloaded yet.

Stage Numero Dos

Thingsget a bit more exciting with the second stage where the raw markup andDOM of your page has been loadedvà parsed:


The thing to note about this stage is that external resources likeimages & stylesheets have sầu not been parsed. You only see the rawnội dung specified by your page/document"s markup.

Stage Numero Three

The final stage is where your page is fully loaded with any images,stylesheets, scripts, và other external resources making their way inlớn what yousee:


This is the stage where your browser"s loading indicators stopanimating, và this is also the stage you almost always find yourself in wheninteracting with your HTML document.

Xem thêm: Xét Nghiệm Tg Là Gì ? Tg Chỉ Số Tg Trong Máu Là Gì

Now that you have a basic idea of the three stages your document goesthrough when loading content, let"s move forward to the more interestingstuff. Keep these three stages at the tip of your fingers (or under yourhat if you are wearing one while reading this), for we"llrefer baông xã lớn these stages a few times in the following sections.

The DOMContentLoaded and load Events

There are two events that represent the two importants milestoneswhile your page loads. The DOMContentLoaded event firesat the kết thúc of Stage #2 when your page"s DOM is fully parsed.The load event fires at the kết thúc of Stage#3 once your page has fully loaded. You can use these events to lớn timewhen exactly you want your code khổng lồ run.

Below is a snippet of these events in action:

document.addEventListener("DOMContentLoaded", theDomHasLoaded, false);window.addEventListener("load", pageFullyLoaded, false);function theDomHasLoaded(e) // vì somethingfunction pageFullyLoaded(e) // vì something againYou use these events just like you would any otherevent, but the main thing lớn note about these events is that youneed khổng lồ listen to DOMContentLoaded from thedocument element và loadfrom the window element.

Now that we got the boring technical details out of the way, why are these events important? Simple. If you have any codethat relies on working with the DOM such as anything that uses thequerySelector orquerySelectorAll functions, you want toensure your code runs only after your DOM has been fully loaded. If you try toaccess your DOM before it has fully loaded, you may get incompleteresults or no results at all.

A sure-fire way lớn ensure you never get inlớn a situation where yourcode runs before your DOM is ready is to lớn listen for the DOMContentLoaded event and let all ofthe code that relies on the DOM to run only after that event isoverheard:

document.addEventListener("DOMContentLoaded", theDomHasLoaded, false);function theDomHasLoaded(e) var images = document.querySelectorAll("img"); // vị something with the imagesFor cases where you want your code to run only after your pagehas fully loaded, use the load event. Inmy years of doing things in JavaScript, I never had too much usefor the load event at the document leveloutside of checking the final dimensions of a loaded image or creating acrude progress bar to lớn indicate progress. Your mileage may vary, but...I doubt it :P

Scripts & Their Location in the DOM

In theWhere Should Your Code Live sầu tutorial, we looked at the various waysyou can have scripts appear in your document. You saw that your scriptelements" position in the DOM affects when they run. In this section, weare going to re-emphaform size that simple truth and go a few steps further.

To review, a simple script element can be somecode stuck inline somewhere:

A simple script element can also be something that references somecode from an external file:

Now, here is the important detail about these elements. Your browserparses your DOM sequentially from the top to the bottom. Any scriptelements that get found along the way will get parsed in the order theyappear in the DOM.