forked from loverajoel/jstips
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
db508bd
commit c758d53
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
--- | ||
layout: post | ||
|
||
title: Detect document ready in pure JS | ||
tip-number: 46 | ||
tip-username: loverajoel | ||
tip-username-profile: https://www.twitter.com/loverajoel | ||
tip-tldr: The cross-browser way to check if the document has loaded in pure JavaScript | ||
|
||
categories: | ||
- en | ||
--- | ||
|
||
The cross-browser way to check if the document has loaded in pure JavaScript is using [`readyState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState). | ||
|
||
```js | ||
if (document.readyState === 'complete') { | ||
// The page is fully loaded | ||
} | ||
``` | ||
|
||
You can detect when the docuemnt it's ready... | ||
|
||
|
||
```js | ||
let stateCheck = setInterval(() => { | ||
if (document.readyState === 'complete') { | ||
clearInterval(stateCheck); | ||
// document ready | ||
} | ||
}, 100); | ||
``` | ||
|
||
or with [onreadystatechange](https://developer.mozilla.org/en-US/docs/Web/Events/readystatechange)... | ||
|
||
|
||
```js | ||
document.onreadystatechange = () => { | ||
if (document.readyState === 'complete') { | ||
// document ready | ||
} | ||
}; | ||
``` | ||
|
||
Use `document.readyState === 'interactive'` to detect when the DOM is ready. |