[removed] equivalent for Ajax applications?

后端 未结 5 700
情话喂你
情话喂你 2020-12-12 02:01

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 scri

5条回答
  •  生来不讨喜
    2020-12-12 02:18

    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 ...
            //
        }
    }
    

提交回复
热议问题