Search code examples
javascriptdomdom-eventsrenderingpageload

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?


Solution

  • 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.