Is it ok to manipulate dom before ready state?

孤街浪徒 提交于 2019-11-27 21:34:10

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

You can manipulate the DOM before it has fully loaded, but it can be risky. You obviously can't guarantee that the bit of the DOM you are trying to manipulate actually exists yet, so your code may fail intermittently.

As long as you only modify nodes which preceed the script block (ie the node's closing tag preceeds the script's opening tag), you shouldn't encounter any problems.

If you want to make sure the operation succeeds, wrap the code in a try...catch block and call it again via setTimeout() on failure.

In Viajeros.com I have a loading indicator working since 8-9 months and I have no problems so far. It looks like this:

<body>

<script type="text/javascript">
    try {
        document.write('<div id="cargando"><p>Cargando...<\/p><\/div>');
        document.getElementById("cargando").style.display = "block";
    } catch(E) {};
</script>

Accessing the DOM prematurely throws exceptions in IE 5 and Navigator 4.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!