Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to manipulate dom before ready state?

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.

like image 933
meandmycode Avatar asked Aug 03 '09 15:08

meandmycode


3 Answers

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

like image 141
Andrew Martinez Avatar answered Oct 02 '22 09:10

Andrew Martinez


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.

like image 31
Rik Heywood Avatar answered Oct 02 '22 09:10

Rik Heywood


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.

like image 43
Christoph Avatar answered Oct 02 '22 10:10

Christoph