window.onload何时触发? [英] When is window.onload fired?

查看:120
本文介绍了window.onload何时触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于何时触发window.onload事件,我有些困惑.例如:我有一个页面,其中包含许多外部js文件,甚至按需加载脚本(动态创建标签).所有这些代码都在页面中(即,不会在单击或触发时触发,应在加载时执行).现在,让我们说我在最后一个按需JavaScript中具有window.onload = somefunction().可能在所有脚本实际加载之前触发window.onload吗?

I'm a bit confused as to when the window.onload event is fired. For example: i have a page that has lots of external js files and even an on-demand loading of the script (dynamically creating a tag). All of this code is in the page (ie. it does not get fired on click or smth, it should execute while loading). Now let's say that i have window.onload = somefunction() in the last on-demand javascript. Is it possible that window.onload will fire before all the scripts actually get loaded?

推荐答案

window.onload (又名 body.onload )在主HTML,所有CSS,所有图像和所有其他资源均已加载和渲染.因此,如果您的图像停滞了,那可能要花一些时间.

window.onload (a.k.a body.onload) gets fired after the main HTML, all CSS, all images and all other resources have been loaded and rendered. So if your images stall, that can take some time.

如果只需要HTML(DOM),则可以使用jQuery的 $(document).ready()-在解析HTML之后但在浏览器完成所有加载之前,它将触发外部资源(图像和样式表,该样式表位于HTML中的脚本元素之后).

If you just need the HTML (DOM), you can use jQuery's $(document).ready() - it will fire when the HTML has been parsed but before the browser has finished loading all external resources (images and style sheets that come after your script element in the HTML).

脚本.因此,要在其他任何脚本之前执行脚本,请在< head> 之后的标头中添加< script> 标记.

Scripts embedded in the page get executed when the browser parses the </script> of each. So to execute a script before any other script, add a <script> tag in the header just after <head>.

这意味着您可以通过添加< script> 标签作为< body>的最后一个元素来模拟" window.onload 代码>.

This means you can "emulate" window.onload by adding a <script> tag as the last element of the <body>.

这篇关于window.onload何时触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆