views:

52

answers:

4

I have a few dynamic pages and I want to alter certain elements before the page has fully rendered.

My snippet is something like

document.body.getElementById("change").innerHTML = "<img src...";

I do not have access to change the content server side.

Where is the best place to put the snippet to have the code run before the page it has rendered?

Rather, is putting the javascript in either the HEAD (inside the window.onload event?) or before the closing BODY(not inside an event listener) optimal?

+1  A: 

AFAIK you cannot do this. Because before a page is rendered there won't be any element and you can't access elements that haven't been loaded to the DOM tree.

rahul
+2  A: 

I'm afraid you are highly unlikely to be able to execute your script before the page renders. Sure you can place an inline script and have it use document.write(...) at the place you'd like it to display your content, but this is a horrible solution. Orherwise the best you can do is at the 'DOM Ready' event, although it's difficult to do on all browsers consistently, you really need a library to abstract the details. jQuery provides it's ready method to fire an event when the DOM is ready, rather than when the page and all resources are finished loading.

Geoff
A: 

Since the browser usually renders elements immediately after they have been parsed the best way would be do place the code in a script element directly after the referenced element:

<div id="change"></div>
<script type="text/javascript">
    document.body.getElementById("change").innerHTML = "<img src...";
</script>
RoToRa
+1  A: 

Not sure I understand your problem correctly, but if you use an event listener inside the head (such as jQuery's $(document).ready()), you will be able to alter the element once the dom structure has been loaded by passing your snippet to the function (handler) being called when the event fires.

<HEAD>
    //...
    <SCRIPT type="text/javascript">

        $(document).ready(function() {
            $("#change").append(
                $("<img src=\"...\">") 
            ) ;
        }) ;

    <SCRIPT>

</HEAD>

Using core javascript you will have to fork your event listeners for mozilla (W3C) and internet explorer event specifications. There's loads of documentation on how to do that on the internet.

Either way the best thing to do in this case obviously would be to create the content yourself, not altering it post rendering.

FK82