Question

I'm using window.onload to call my JavaScript code that has to be executed after the page is fully loaded. From what I read this is the recommended method to call such scripts.

However, it does not work for some Ajax sites, www.bing.com for instance - window.onload is called before the pages is fully rendered.

Any suggestions?

Was it helpful?

Solution

The short answer is that there's no general way to solve this problem (right now).

The definition of a "page" is pretty fungible when AJAX comes into play - it's pretty hard to tell the difference between AJAX that is intended to be part of the initial page load, and that which might not be. So, browsers are left on their own to determine when window.onload() should be fired, and it doesn't always end up where you want.

Luckily, most people don't need a general solution, but rather a specific one. If you care about bing.com, then you can probably look at how bing.com works and design your code to trigger when the site reaches a state that you find acceptable.

OTHER TIPS

You might be able to listen for changes and requests by globally listening for DOMSubtreeModified and readystatechange events, and use those events instead of the load event for whatever you are trying to do.

I've wrestled with this a couple of times, and my usual reason for needing some sort of onload event triggering is to be able to interact with the HTML DOM and have getElementById, getElementsByTagName, or various other DOM selectors, return something other than nothing.

Once again, I'm not sure of the exact problem you are trying to solve, but if you must use some sort of onload, and it's because of DOM traversal of some kind, you can cheat a bit with the following sort of code:

window.onload = pageChecker;

function pageChecker() {
    // Onload has fired, but we don't trust it.
    // Check to see if our deepest nested element can be found
    var testElement = document.getElementById("importantElement");

    if ( !testElement ) {
        // Try again in a bit, adjust timeout to what your users
        // can tolerate
        setTimeout(pageChecker, 50);
    }
    else {
        //
        // ... the element exists, run important code below ...
        //
    }
}

I'd recomend using jQuerys $(...).ready() method.

In addition to the answer from Rasmus Kaj and if you are using jQuery, I would direct you to take a look at Global Ajax Event Handlers.

Note, that this has nothing to do with the native onload event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top