how to run jquery code after content loads?

I have a situation where I load a parent web page (happens to be Java JSP) which has content I am loading using ajax (asynch) inside of a document ready function expecting the page to render whatever it can quickly then run the jquery code to perform asynch work after the page is displayed.

It works just as expected in firefox - page renders quickly and then the jquery code runs ajax calls loading other elements.

In IE8 it waits until everything is done, then renders the completed results. It does not honor my document ready attempt. It sits there loading the page while running my code in the document ready section, then finally the completed results of everything is plopped on the browser.

Is there any workaround? Any way to get IE8 to behave like Firefox in this regard ... render the page ASAP and then run some jquery code/ajax calls AFTER rendering?


This is a bug that affects IE6 7 and 8. jQuery's document ready handler doesn't fire until right before or right after the window load event in IE 6 7 and 8. This does not happen in IE9.

One way to fix it is to handle the event yourself.

<body class="jquerydomready">
    <!--[if lt IE 9]>
    <script>
        $('body').removeClass('jquerydomready');
    </script>
    <![endif]-->

and then in your script use this:

function init() {
    // code here will be ran when document is ready
    $("body").css("background-color","green");
}

if ( $("body").is(".jquerydomready") ) {
    $(init); // not oldIE
}
else {
    // oldIE way
    document.onreadystatechange = function() {
        if (document.readyState == "interactive") init();    
    }​
}

Keep in mind though that if you are performing ajax requests and expecting them to happen quickly or else code won't work, i suggest moving to a system that doesn't require them to happen quickly because you can't rely on the network always being quick.

ticket: http://bugs.jquery.com/ticket/12282

It currently is not actually marked as a bug, but if you follow the history on this issue it has been fixed and unfixed several times throughout the development of jQuery.

Edit: I'm not entirely sure on the IE6 part of this answer, i haven't tested IE6 with this.

Here's a supporting JSFiddle showing that it improperly waits in IE7 and 8 (again not tested in IE6).

Before the above fix: http://jsfiddle.net/PFWmS/

After the above fix: http://jsfiddle.net/PFWmS/7


你有没有尝试将你的部分移动到页面的末尾?

链接地址: http://www.djcxy.com/p/71254.html

上一篇: JQuery只会在Rails 4应用程序的页面刷新中加载

下一篇: 内容加载后如何运行jquery代码?