How to wait for jQuery's load function to render loaded content before executing callback function

时间秒杀一切 提交于 2019-12-22 06:47:41

问题


I am using jQuery's load function to render some of my content when the document is ready.

$(document).ready(function(){
   $('#header').load('header.html',function() {
      //do call back function});
   $('#footer').load('footer.html');
});

I don't want my callback function to execute when the request completes, but rather when the loaded content (or dom?) is ready to be manipulated. How can I do this?

Thanks


回答1:


I'm pretty sure your looking to do something after the Window is loaded, not the DOM.

If you have some code the relies on reading the heights and widths of things like images, (document).ready will not work because it is run before the images have been loaded. I've had this problem before when trying to render RSS feeds on a page.

This is the code to do something after the window is loaded:

jQuery(window).load(function() {
    //Do something after the window is loaded!
});



回答2:


From what I understand the problem here is that the callback gets called as soon as the data is received rather than when the browser has finished rendering it. This is a problem if your callback relies on style properties as one example.

My solution has been to hide the parent node before loading, then adding in a slight delay before showing it again, with a callback placed on the show method.

$('#header').hide().load('header.html').delay(1).show(0, function(){
    //callback statements
});

So this works but isn't bulletproof as we don't know exactly how long the content will take to render.



来源:https://stackoverflow.com/questions/3085954/how-to-wait-for-jquerys-load-function-to-render-loaded-content-before-executing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!