Implement the js method to run after the HTML page is loaded

小云云
Release: 2018-03-30 15:51:07
Original
3297 people have browsed it

This article mainly shares with you the method of running js after the HTML page is loaded. It mainly shares with you the code method. I hope it can help you.

Js method:

Copy after login

jQuery method, you need to quote the jQuery file:

Copy after login

or its abbreviation:

$(function (){var userName=”xiaoming”; alert(userName); });
Copy after login

It can be executed after the DOM is loaded ( earlier than window.onload). .ready() can appear multiple times in the same page

The main difference between the two is: Window.onload=function (){}:

When a document is completely downloaded to the browser, Only then will the window.onload event be triggered. This means that all elements on the page are operable for js, which means that all elements on the page will not be executed until they are loaded. This situation is very advantageous for writing functional code because there is no need to consider the order of loading.

$(document).ready(function (){});

will be called when the DOM is completely ready and ready for use. While this also means that all elements are accessible to the script, it does not mean that all associated files have been downloaded. In other words, the code is executed after the HTML is downloaded and parsed into a DOM tree.

Using $(document).ready(function (){}) is generally better than using onload event handler, but it must be clear, because the support file may not be loaded yet, so something like Properties such as image height and width are not necessarily valid at this time.

Note: There will be problems with placing js at the bottom of the page and using defer="defer". It's better to use the $(document).ready(function (){}) function.

Related recommendations:

Introduction to speeding up HTML page loading

The above is the detailed content of Implement the js method to run after the HTML page is loaded. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!