问题
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?
回答1:
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.
回答2:
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.
});
回答3:
<body onload="start()">
</body>
In the function start the DOM is guaranteed to be loaded.
回答4:
var firstLoad = true;
$(document).ready(function(){
if ( firstLoad ){
firstLoad=false;
//your code to run once
}
});
回答5:
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>
来源:https://stackoverflow.com/questions/4270431/check-from-bookmarklet-whether-page-is-loaded