在准备状态之前操纵dom可以吗? [英] Is it ok to manipulate dom before ready state?

查看:107
本文介绍了在准备状态之前操纵dom可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这通常是如何管理渐进式增强,同时保持体验清洁,但它是多么安全?有没有竞争条件的潜力,这不工作?



想象一下简单的抽象场景,如果你有javascript支持,你想要显示不同的东西..这通常是什么我会最终做:

 < div id =test> original< / div> 
< script type =text / javascript>
var t = document.getElementById('test');
t.innerHTML ='changed';
< / script>

许多人可能会声称您应该使用框架并等待domready事件,并在那里进行更改。然而,在测试元素已经在文档结束之前已经被渲染并且css准备好并且domready被触发的情况下存在显着的延迟,从而导致原始的显着闪烁。



这段代码是否有可能导致竞争条件失败?或者我可以保证,如果元素在脚本之前存在,可以发现和修改元素?



提前感谢

解决方案

你可以,但是有一些问题。



首先,在IE中,如果您尝试操纵一个节点那个还没有被关闭(例如BODY之前的关闭标签应该在你的JS之下),那么你可能会遇到IE的OPERATION ABORTED错误,这将导致一个空白页面。节点的操作包括附加节点,移动节点等。



在其他浏览器中,行为是未定义的,但是它们的行为通常与您期望的一样。主要问题是,随着您的页面的发展,页面可能会加载/解析/运行不同。这可能会导致某些脚本在浏览器定义引用的元素实际已创建并可用于DOM操作之前运行。



如果您尝试增强用户感知的性能(即snappiness)。我强烈建议您避免这个路径,并寻找减轻你的页面。您可以使用雅虎的YSlow / Google的页面性能Firebug来帮助您开始使用。



Google的页面速度



雅虎的YSlow


This is generally how I manage progressive enhancement whilst keep the experience clean, but how safe is it? is there potential for a race condition and this not working?

Imagine the simple abstract scenario, you want to display something differently if you have javascript support.. this is generally what I will end up doing:

<div id="test">original</div>
<script type="text/javascript">
    var t = document.getElementById('test');
    t.innerHTML = 'changed';
</script>

Many may claim you should use a framework and wait for a domready event, and do changes there.. however there is a significant delay where the 'test' element will have already been rendered before the end of the document and the css are ready and a domready triggers.. thus causing a noticable flicker of 'original'.

Is this code liable to race condition failures? or can I guarentee that an element is discoverable and modifiable if it exists before the script?

Thanks in advance.

解决方案

You can, but there are issues surrounding doing it.

First off, in IE if you attempt to manipulate a node that has not been closed (e.g. BODY before its close tag which should be below your JS) then you can encounter IE's "OPERATION ABORTED" error which will result in a blank page. Manipulation of a node includes appending nodes, moving nodes, etc.

In other browsers the behavior is undefined, however they do usually behave as you would expect. The main issue is that as your page evolves, the page may load/parse/run differently. This may cause some script to run before a browser defines referenced elements have actually been created and made available for DOM manipulation.

If you are attempting to enhance your user perceived performance (i.e. snappiness). I highly suggest that you avoid this path and look into lightening your pages. You can use Yahoo's YSlow/Google's Page Performance Firebug to help you get started.

Google's Page Speed

Yahoo's YSlow

这篇关于在准备状态之前操纵dom可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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