简体   繁体   English

Javascript:在document.onload之前访问DOM

[英]Javascript: accessing DOM before document.onload

I have a page which has document.body.onload=function(){...} but this is suffering delays because the document also contains external <img> tags etc; 我有一个包含document.body.onload=function(){...}的页面,但是由于文档中还包含外部<img>标记等,因此这会造成延迟 onload seems to be only getting fired after these external sites have delivered some kind of response. 在这些外部站点做出某种响应之后,似乎只会触发onload

I put the code in onload because I thought the DOM tree wasn't fully available until then (eg document.getElementById(x) might return null if it is called too soon). 我把代码放在onload因为我认为DOM树直到那时才完全可用(例如,如果调用太早,document.getElementById(x)可能会返回null)。

Is there an event which triggers after everything in the DOM is accessible, but before everything has been loaded? 是否有事件可以在DOM中的所有内容都可以访问之后但在所有内容加载之前触发?

You can just place your <script> tag at the end of the body since the html is parsed in sequence. 您可以将<script>标记放在正文的末尾,因为html是按顺序分析的。

Additionally, you could look at jquery 's document.ready. 另外,您可以查看jquery的document.ready。 Even if you don't want to use jquery, you can have a look at how they handle it. 即使您不想使用jquery,也可以看看他们如何处理它。 ready does exactly what you're asking for. ready完全符合您的要求。

Sure you can: 你当然可以:

Maybe you have two options: 也许您有两个选择:

1) by using jQuery: with $(document).ready() , you can get your events to load or fire or whatever you want them to do before the window loads. 1)通过使用jQuery:与$(document).ready() ,您可以加载或触发事件,或者在窗口加载之前希望事件执行任何操作。

2) DOMContentLoaded Reference: https://developer.mozilla.org/en/DOM/DOM_event_reference/DOMContentLoaded 2)DOMContentLoaded参考: https : //developer.mozilla.org/en/DOM/DOM_event_reference/DOMContentLoaded

function checkDom(yourFunc)
{
     window.addEventListener('DOMContentLoaded', yourFunc);
}

You should consider if you really need the whole document loaded. 您应该考虑是否真的需要加载整个文档。 As long as your libraries are already loaded and the DOM nodes you are interested in are on the page, you can act immediately. 只要您的库已经加载并且您感兴趣的DOM节点都在页面上,您就可以立即采取行动。 This sort of code makes a page "come alive" much faster than one that waits for every last resource to load: 这种代码使页面“活跃起来”的速度比等待每个最后一个资源加载的页面快得多:

<form name="foo">
    <!-- ... -->
</form>
<script>
    var form = new My.FormWidget(document.forms.foo);
</script>

This has the added benefit of forcing you to encapsulate logic in the FormWidget (you should want to keep an "inline" script like that as brief as possible). 这具有强制您将逻辑​​封装在FormWidget的附加好处(您应该希望保持这样的“内联”脚本尽可能简短)。

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

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