简体   繁体   English

window.onload在Javascript中的位置

[英]Position of window.onload in Javascript

I have a javascript code like this 我有这样的JavaScript代码

<script type="text/javascript">
window.onload=myFunction;
</script>

Is there any difference in using the above snippet in the <head></head> tag and just before </body> tag, as I would like to call my function after the page loads. <head></head>标记和</body>标记之前使用上面的代码片段有什么区别,因为我想在页面加载后调用我的函数。

basically there's no pratical difference, but I recommend 基本上没有实际差异,但我建议

  1. to place that code at the bottom, since you need to use a script (blocking-rendering tag) it's better put it at the end of the document. 将代码放在底部,因为您需要使用脚本(blocking-rendering标签),所以最好将其放在文档的末尾。

  2. to avoid a destructive assignments like that: writing window.onload=myFunction you destroy other previous assignments to window.onload event (if any) so it's better something like 为了避免这样的破坏性分配:编写window.onload=myFunction可以销毁对window.onload事件的其他先前分配(如果有的话),所以最好是这样

     (function() { var previousOnLoadIfAny = window.onload; window.onload = function() { if (typeof previousOnLoadIfAny === 'function') { previousOnLoadIfAny(); } yourfunction(); } }()); 

Binding to window.onload will always run your function when the load event fires. load事件触发时,绑定到window.onload将始终运行您的函数。 This only fires after everything in the page has finished loading, including images etc. If you want to run your function when the DOM has finished loading but before everything else then you can bind to the DOMContentLoaded event or use a library like jQuery (eg $(function(){ myFunction() }); ). 这仅在页面中的所有内容(包括图像等)完成加载后才触发。如果要在DOM完成加载后但在其他所有操作之前运行函数,则可以绑定到DOMContentLoaded事件或使用jQuery之类的库(例如$(function(){ myFunction() }); )。

The benefit about putting your function at the end of your <body> is that theoretically this means that the rest of your content has already loaded and you don't need to bind your function to a load event. 将函数放在<body>末尾的好处是,从理论上讲,这意味着您的其余内容已经加载,并且不需要将函数绑定到load事件。 This sometimes works, but depends on the situation. 有时这可行,但要视情况而定。

No, where you place that will not matter - anywhere in the document and it will trigger when the document and all external resources (images, scripts etc) has loaded. 不,您放置的位置无关紧要-文档中的任何位置,当文档和所有外部资源(图像,脚本等)已加载时,它将触发。

Because onload triggers after all external resources one often want to use DOMContentLoaded instead which triggers when the HTML DOM is ready. 因为onload在所有外部资源之后触发,所以人们通常想使用DOMContentLoaded来代替,而后者在HTML DOM准备就绪时触发。 Which will make for a page that is more responsive. 这将使页面更具响应性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM