Reputation: 909
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().
Upvotes: 4
Views: 2153
Reputation: 25740
The elementReady jQuery plugin lets you run code as soon as an element loads. Especially useful for dynamically loaded elements. (I wrote this plugin.)
Upvotes: 1
Reputation: 32189
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.
Upvotes: 3
Reputation: 2069
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
});
Upvotes: 0
Reputation: 32223
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.
Upvotes: 0
Reputation: 700152
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.
Upvotes: 5
Reputation: 35363
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>
Upvotes: -2