admin管理员组文章数量:1355535
I have a javascript code like this
<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.
I have a javascript code like this
<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.
- "in tag and just before tag" - what do you mean by this? "tag" would refer to? – thomthom Commented Mar 19, 2012 at 9:46
- @Prabhavith what do you mean by (in tag and just before tag) – mgraph Commented Mar 19, 2012 at 9:46
-
Also, you want to call your script after all images and external resources has loaded? Or just after the HTML is ready - in which you want to use the
DOMContentLoaded
instead. – thomthom Commented Mar 19, 2012 at 9:47 -
i guess he thinks about
<body onload="...">
– Christoph Commented Mar 19, 2012 at 9:48
3 Answers
Reset to default 4basically there's no pratical difference, but I remend
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.
to avoid a destructive assignments like that: writing
window.onload=myFunction
you destroy other previous assignments towindow.onload
event (if any) so it's better something like(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. 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 (e.g. $(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. 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. Which will make for a page that is more responsive.
本文标签: htmlPosition of windowonload in JavascriptStack Overflow
版权声明:本文标题:html - Position of window.onload in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743973020a2570766.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论