Javascript – How to verify if a webpage is completely loaded using javascript

javascriptjavascript-events

I need to disable an image which I am using in <a "href"> until the page completely loads.

I cannot use document.ready() because I need to disable the the BEFORE the document is ready.

Can someone please help me with this?

Regards,
Gnanesh

Best Answer

Define it in your HTML as disabled:

<button disabled="disabled">My Button</button>

And then on page load re-enable it.

This has the downside of breaking functionality for users without Javascript. The other way to do it is to add a small line of code directly after the button:

<button id="myButton">My Button</button>

<script type="text/javascript">
    document.getElementById('myButton').disabled = true;
</script>

...and then re-enable on document.load()

Edit with new info:
Is it an input with type "image"? If so, the above will still work. If not, and it's an <a> tag with an image inside it, I wouldn't recommend doing what the accepted answer suggests, sorry. Having an image suddenly appear at the end could get quite frustrating or distracting, considering that the page takes so long to load that you need to disable the link. What I'd suggest instead is this:

<a href="whatever" onclick="return myLinkHandler();"><img src="..." /></a>
<script type="text/javascript">
    var myLinkHandler = function() {
        alert('Page not loaded.');  // or something nicer
        return false;
    };
</script>

and then in your document.ready function, change the definition of the function:

myLinkHandler = function() {
    alert("Yay, page loaded.");
    return true;
};

Alternatively, you could put a check inside the function to see if the page has loaded or not.

var documentReady = false;
function myLinkHandler() {
    alert (documentReady ? "Ready!" : "Not ready!");
    return documentReady;
}

document.onload = function () { // or use jQuery or whatever
    documentReady = true;
};
Related Topic