Home Web Front-end JS Tutorial JavaScript techniques for determining when the DOM is loaded_javascript techniques

JavaScript techniques for determining when the DOM is loaded_javascript techniques

May 16, 2016 pm 05:48 PM
dom judgment load

One difficulty with working with HTML DOM documents is that JavaScript can be executed before the DOM is fully loaded, which can cause a lot of potential problems for your code. The rendering and operation sequence of the browser is roughly as follows:

HTML parsing completed
External scripts and style sheets loaded
Scripts are parsed and executed within the document
HTML DOM is fully constructed
Images and external content loading
Web page completes loading

Scripts in the head of the web page and loaded from external files will be executed before the HTML is actually constructed. As mentioned before, this is a critical issue because the scripts executed in these two places cannot access the DOM that does not yet exist. Fortunately, we have several remedies.
Currently, the most commonly used level is to completely wait for the entire page to load before performing DOM operations. This technology only needs to use the load event of the window object to bind a function, which can be triggered after the page is loaded.

Copy code The code is as follows:

addEvent(window, "load", function(){
// do something
});

The simplest operation is the slowest. In the sequential list of the loading process, you will notice that whether the page is loaded or not is completely controlled by the last step. This means that if the page has a lot of pictures, videos, etc., the user may have to log in for a while before JavaScript is executed.
Another progression can be used to listen to DOM loading status, probably the most complex (from an implementation perspective), but also the most efficient.
This technology checks whether the HTML DOM document has been loaded with the attributes necessary for execution as quickly as possible without blocking the browser loading. Here are a few key points for checking whether the HTML DOM is available:

document: You need to know whether the DOM document has been loaded. If you check quickly enough, with luck you'll see undefined.
document.getElementsByTagName and document.getElementById: Frequently use the document.getElementsByTagName and document.getElementById functions to check the document. When these functions exist, it indicates that the DOM has been loaded.
document.body: As an added bonus, checks if the element has been fully loaded. Theoretically the previous check should already be able to make a judgment, but I found that in some cases it's still not enough.
Using these checks is enough to determine whether the DOM is available ("sufficient" here means that there may be a certain millisecond time difference). This method has few flaws. Using the aforementioned checks alone, the script should run relatively well in modern browsers. However, more recently (2008?) Firefox implemented caching improvements such that the window load event can actually fire before the script can check whether the DOM is available. In order to take advantage of this, I also attached checks to the window loading event in order to achieve faster execution speed.

Finally, the domReady function collects references to all functions that need to be executed when the DOM is available. Once the DOM is considered available, these references are called and executed one by one in sequence.
Copy code The code is as follows:

// The function that monitors whether the DOM is available
function domReady(f) {
// If the DOM has been loaded, Mashan executes the function
if(domReady.done) return f();

// If we have added a function
if(domReady.timer) {
// Assume it is in the list of functions to be executed
domReady.ready.push(f);
} else {
// Bind the page after loading An event in case it completes first.
addEvent(window, "load", isDOMReady);
// Initialize the array of execution functions
domReady.ready = [f];
// Check whether the DOM is available as quickly as possible
domReady.timer = setInterval(isDOMReady, 13);
}
}

// Check whether the DOM is operational
function isDOMReady() {
// If we It can be judged that the DOM is possible, ignore
if(domReady.done) return false;

// Check whether several functions and elements are possible
if(document && document.getElementsByTagName && document.getElementById && document.body) {
// If available, we stop checking
clearInterval(domReady.timer);
domReady.timer = null;

// Execute all waiting functions
for(var i = 0; i < domReady.ready.length; i ) {
domReady.ready[i]();
// Record that we have finished here
domReady.ready = null;
domReady.done = true;
}
}
}

Now let’s see how it is performed in an HTML document. Assume that the domReady function has been written to an external file named domready.js
Copy the code The code is as follows:



Testing DOM Loading

<script> <br>domReady(function(){ <br>alert("The DOM is loaded!"); <br>// do something <br>}); <br></script>


Testing DOM Loading





Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Error loading plugin in Illustrator [Fixed] Error loading plugin in Illustrator [Fixed] Feb 19, 2024 pm 12:00 PM

When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

Stremio subtitles not working; error loading subtitles Stremio subtitles not working; error loading subtitles Feb 24, 2024 am 09:50 AM

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

PHP email detection: Determine whether the email has been sent successfully. PHP email detection: Determine whether the email has been sent successfully. Sep 19, 2023 am 09:16 AM

PHP email detection: Determine whether the email has been sent successfully. When developing web applications, you often need to send emails to communicate with users. Whether it is registration confirmation, password reset, or sending notifications, the email function is an indispensable part. However, sometimes we cannot ensure whether the email is actually sent successfully, so we need to perform email detection and determine whether the email has been sent successfully. This article will introduce how to use PHP to implement this function. 1. Use SMTP server to send emails. First, we need to use SM

Use java's File.isDirectory() function to determine whether the file exists and is a directory type Use java's File.isDirectory() function to determine whether the file exists and is a directory type Jul 24, 2023 pm 06:57 PM

Use Java's File.isDirectory() function to determine whether a file exists and is of directory type. In Java programming, you often encounter situations where you need to determine whether a file exists and is of directory type. Java provides the File class to operate files and directories. The isDirectory() function can help us determine whether a file is a directory type. The File.isDirectory() function is a method in the File class. Its function is to determine the current File

PHP implements infinite scroll loading PHP implements infinite scroll loading Jun 22, 2023 am 08:30 AM

With the development of the Internet, more and more web pages need to support scrolling loading, and infinite scrolling loading is one of them. It allows the page to continuously load new content, allowing users to browse the web more smoothly. In this article, we will introduce how to implement infinite scroll loading using PHP. 1. What is infinite scroll loading? Infinite scroll loading is a method of loading web content based on scroll bars. Its principle is that when the user scrolls to the bottom of the page, background data is asynchronously retrieved through AJAX to continuously load new content. This kind of loading method

Outlook freezes when inserting hyperlink Outlook freezes when inserting hyperlink Feb 19, 2024 pm 03:00 PM

If you encounter freezing issues when inserting hyperlinks into Outlook, it may be due to unstable network connections, old Outlook versions, interference from antivirus software, or add-in conflicts. These factors may cause Outlook to fail to handle hyperlink operations properly. Fix Outlook freezes when inserting hyperlinks Use the following fixes to fix Outlook freezes when inserting hyperlinks: Check installed add-ins Update Outlook Temporarily disable your antivirus software and then try creating a new user profile Fix Office apps Program Uninstall and reinstall Office Let’s get started. 1] Check the installed add-ins. It may be that an add-in installed in Outlook is causing the problem.

How to solve the problem that css cannot be loaded How to solve the problem that css cannot be loaded Oct 20, 2023 am 11:29 AM

The solutions to the problem that CSS cannot be loaded include checking the file path, checking the file content, clearing the browser cache, checking the server settings, using developer tools and checking the network connection. Detailed introduction: 1. Check the file path. First, please make sure the path of the CSS file is correct. If the CSS file is located in a different part or subdirectory of the website, you need to provide the correct path. If the CSS file is located in the root directory, the path should be direct. ; 2. Check the file content. If the path is correct, the problem may lie in the CSS file itself. Open the CSS file to check, etc.

Use java's Character.isDigit() function to determine whether a character is a number Use java's Character.isDigit() function to determine whether a character is a number Jul 27, 2023 am 09:32 AM

Use Java's Character.isDigit() function to determine whether a character is a numeric character. Characters are represented in the form of ASCII codes internally in the computer. Each character has a corresponding ASCII code. Among them, the ASCII code values ​​corresponding to the numeric characters 0 to 9 are 48 to 57 respectively. To determine whether a character is a number, you can use the isDigit() method provided by the Character class in Java. The isDigit() method is of the Character class

See all articles