views:

223

answers:

5

Is it possible to detect the exact moment an element exists in the DOM on page load?

Context: On page load i hide an element of my page using jQuery (i.e. If JavaScript is available i want to hide the div) but on poor internet connection you see the panel for a second or so before it disappears.

I'd like to hide the element as soon as it's written to the DOM but i don't know how to do this or even if it's possible. I don't want to apply set display:hidden because i want to the panel to appear if JavaScript isn't available.

TIA

Matt

Revision: I'm using jQuery - and my code in executed from within $(document).ready().

A: 

I was going to suggest something like the following, but I don't think it will work:

<noscript>
  <style type="text/css">
     div.myblock { display: visible; }
  </style>
</noscript>
richardtallent
+3  A: 

That's what the <noscript> tag is there for.

<noscript>This site works better with Javascript enabled.</noscript>

It will only display the contents if scripting is disabled.If Javascript is enabled, the contents will not be displayed. That sounds like exactly the behavior you are looking for.

William Brendel
I like this answer - should have though about <noscript>. In the back of my mind i've got a query about this being depreciated.. but i could be wrong.
Matt Goddard
As far as I know it is not being depreciated any time soon. It is also being carried forward as part of HTML5.
William Brendel
+3  A: 

Put the javascript right after the element, that will minimise the time that the element may be visible:

<div id="CrouchingTiger">HiddenDragon</div>
<script type="text/javascript">
document.getElementById('CrouchingTiger').style.display = 'none';
</script>

The script will run while the page is loading, as soon as the end tag of the script has been parsed.

Guffa
in terms of a coding strategy this seems to be the only way. Initially i discounted it because didn't want a script tag in the body of my code.
Matt Goddard
Yes, having scripts in the body is not the first thing to wish for, but it's the only way to run the script before the document is completely loaded.
Guffa
A: 

Try using document ready event instead of Load event as Load event may take time to fire even though DOM may have been loaded.

And if you are really desperate, try this:

<div id="divToHide">

</div>

<script>document.getElementById('divToHide').style.display = 'none';</script>

If browser sees a script tag like above, it will run the JavaScript right away.

SolutionYogi
A: 

Instead of page load, use $(document).ready(). It runs after the DOM is loaded, but before the page contents are loaded.

  $(document).ready(function() {
      // code goes here
  });
Detect