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:
jQuery method, you need to quote the jQuery file:
or its abbreviation:
$(function (){var userName=”xiaoming”; alert(userName); });
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!