Where is the best place to place a javascript snippet to change the DOM of the page before it displays

I have several dynamic pages, and I want to change some elements before the page is fully displayed.

My snippet is something like

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

I do not have access to change the content server.

Where is the best place to put a piece of code to run the code in front of the page that it displays?

Rather, put javascript in HEAD (inside the window.onload event?) Or before closing BODY (not inside the event listener)?

+6
javascript dom javascript-events rendering pageload
source share
5 answers

AFAIK you cannot do this. Since there will be no element before rendering the page, and you will not be able to access elements that have not been loaded into the DOM tree.

0
source share

I am afraid that you are unlikely to be able to execute your script before the page is displayed. Of course, you can place the built-in script and use its document.write (...) in the place where you want to display it, but this is a terrible solution. Orherwise the best you can do is the DOM Ready event, although it is difficult to do this in all browsers in sequence, you really need a library to abstract the details. jQuery provides a ready-made method for triggering an event when the DOM is ready, and not after the page and all resources have finished loading.

+2
source share

Since the browser usually displays the elements immediately after they are analyzed, the best way is to place the code in the script element immediately after the reference element:

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

I'm not sure that I understand your problem correctly, but if you use an event listener inside the head (for example, jQuery $(document).ready() ), you can change the element after loading the dom structure, passing the fragment the function ( handler ) is called when it is triggered events.

 <HEAD> //... <SCRIPT type="text/javascript"> $(document).ready(function() { $("#change").append( $("<img src=\"...\">") ) ; }) ; <SCRIPT> </HEAD> 

Using basic javascript, you will need to develop event listeners for the mozilla (W3C) and Internet Explorer event specifications. There is a lot of documentation on how to do this on the Internet.

In any case, the best thing to do in this case, obviously, it would be to create the content yourself, without changing it after rendering.

+1
source share

If you do not want to display any elements before making DOM changes, you can set CSS display: none in the body element, and then change it to display: block after that.

0
source share

All Articles