Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are several ways to execute js pages after loading?

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

js页面加载后执行的几种方式分别是什么,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

在实际应用中往往需要在页面加载完毕之后再去执行相关的js代码,之所以这么操作是有道理的,如果是操作dom元素,如果相关元素没有加载完成,而去执行js代码,可能会导致错误,下面就介绍一下如何实现页面加载完成再去执行代码,这是最为基础的知识了,可能初学者还不太了解,寄希望能够给需要的朋友带来一定帮助。

一._window.onload事件:

代码如下:

原生js

_window.onload=function(){ //code}

jquery

$(window).load(function(){//code});

当页面完全加载完毕之后再去执行code代码。说明页面需要dom操作,必须到最后才可以执行。

二.使用jQuery的ready事件:

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

一般

(function () {//code}})();

当稳当结构加载完毕再去执行code代码。

通用的页面加载后再运行JS有两种方式:1、在DOM加载完毕后,页面全部内容(如图片等)完全加载完毕前运行JS。 2、在页面全部内容加载完成(包括引用文件,图片等)之后再加载JS

1、在DOM加载后,全部内容加载前运行这种方式在同一文件中可以运行多个且不会覆盖。

由于在$(document).ready()方法只要DOM就绪就会被执行,因此可能此时元素的关联文件未下载完。例如与图片有关的HTML下载完毕,并且已经解析为DOM树了,但很有可能图片还未加载完毕,所以例如图片的高度和宽度这样的属性此时不一定有效。要解决这个问题,可以使用Jquery中 load()方法在需要的文件加载完毕后对其进行操作。

$(document).ready(function(){});$().ready(function(){}) //简写 当$()不带参数时默认就是document$(function(){}); //简写

2、在全部内容加载后运行这种方式中只能执行一个 onload代码,当文件由多个onload或者load,只加载最后一个,前面的将会被覆盖且前面的onload里面的代码不会执行。

_window.onload = function(){}; // --js $(window).load(function(){}); //---jquery

3、DOM文档加载步骤

1.解析HTML结构2.加载外部的脚本和样式文件3.解析并执行脚本代码4.执行$(function(){})内对应代码5.加载图片等二进制资源6.页面加载完毕,执行_window.onload

补充:

1:$(function){};

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

3:$(window).load(function(){});

4:_window.onload = function(){};

5:在标签上静态绑定onload事件,

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report