Reputation: 3774
I'm writing a bookmarklet javascript. The problem here is that it can be invoked by user before and after some page has finished loading. I want to ensure that the sript is run only after the page has finished loading. How to do that?
Upvotes: 4
Views: 2079
Reputation: 21899
Hooking a function to the document's ready/load function ensures nowhere in your code can be executed before the DOM is loaded.
<html>
<body onload="documentLoad()">
<script type="text/javascript">
function documentLoad() {
alert("Document is ready now.");
}
</script>
</body>
</html>
If you want to use jQuery, you can use a very short-hand method to attach all your code to the ready function.
$(document).ready(function() {
// All code in here - will trigger when DOM is loaded.
}
And here is an even shorter short-hand method, using jQuery, to achieve the same.
$(function(){
// All code in here - will trigger when DOM is loaded.
});
Upvotes: 2
Reputation: 21899
Most answers here are answering how to attach a function to the document ready function, which isn't what davidgale is asking...
The document
object has a property of readyState
which will be set to "complete"
when it has finished loading.
<html>
<body>
<script type="text/javascript">
function someFunction() {
// Called various times throughout page's life.
if(document.readyState == "complete") {
// Perform DOM actions - will only attempt after DOM is loaded.
}
}
</script>
</body>
</html>
Upvotes: 0
Reputation: 18522
One way for checking if document has loaded, is to check the document.readyState property. IE, Firefox 3.6+, Webkit and Opera support it.
if (document.readyState === "complete") {
// do sth
}
Another thing is, if you want to wait for the document to load. In that case you have to listen to some events, like DOMContentLoaded on document, load on window or readyStateChange on document.
Upvotes: 3
Reputation: 5358
var firstLoad = true;
$(document).ready(function(){
if ( firstLoad ){
firstLoad=false;
//your code to run once
}
});
Upvotes: 0
Reputation: 1377
<body onload="start()">
</body>
In the function start the DOM is guaranteed to be loaded.
Upvotes: 0