Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the best place to place a Javascript snippet to alter the DOM of a page before it renders

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?

like image 917
markmarkoh Avatar asked Apr 28 '10 10:04

markmarkoh


3 Answers

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.

like image 168
Geoff Avatar answered Oct 24 '22 03:10

Geoff


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>
like image 26
RoToRa Avatar answered Oct 24 '22 03:10

RoToRa


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.

like image 1
FK82 Avatar answered Oct 24 '22 05:10

FK82