开发者

Is there a programatic way of knowing when DOM updates by jQuery have been completed?

开发者 https://www.devze.com 2023-03-06 16:31 出处:网络
For example: var $myContainer = $(\'#myContainer\'); $myContainer.html(someHtml); var width = $myContainer.height();

For example:

var $myContainer = $('#myContainer');
$myContainer.html(someHtml);
var width = $myContainer.height();
var height = $myContainer.height();

If #myContainer was an empty div, width and height would still be zero. A solution is to use a timeout:

var $myContainer = $('#myContainer');
$myContainer.html(someHtml);
setTimeout(function () {
    var width = $myContainer.height();
    var height = $myContainer.height();
}, 500);

However, I don't like the magic number in there. What if its a really slow browser? Is there any reliable cross browser method available to tell me when the browser has render开发者_C百科ed the changes?


You can use 0 for the timeout, reliably. It won't actually be 0ms, you understand, most browsers will make it at least 5 or 10, but just the act of yielding to the browser is sufficient.

That said, I'm not immediately finding a browser that doesn't get the (new) height right immediately, without a yield (even IE6!). But I wouldn't be surprised if, depending on markup and such, there were one...


Feels like a hack but might work: Add a script element to the DOM as the last element. All browsers should execute that after all the other elements have "settled."


Are you using ajax?

So you can use jQuery 'load'.

var $myContainer = $('#myContainer');
$myContainer.load('/url/for/someHtml', function(){
  var width = $myContainer.height();
  var height = $myContainer.height();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消