jQuery .find() fails to find occasionally
I am trying to parse the HTML of a webpage to DOM by loading it into an iframe and do some searching on the DOM afterwards. Here's the code
function f(callback) {
var tmp = document.createElement('iframe');
$(tmp).hide();
$(tmp).insertAfter($('foo'));
$(tmp).attr('src', url);
$(tmp).load(function() {
var bdy = tmp.contentDocument.body;
callback(bdy);
$(tmp).remove();
});
}
In the callback function if I do something like the following
functi开发者_运维问答on callback(bdy) {
alert($(bdy).find('bar').length);
}
sometimes it gives me the correct value but sometimes it gives me 0 instead. However, if I do the following it works
var tmp = document.createElement('iframe');
$(tmp).hide();
$(tmp).insertAfter($('foo'));
$(tmp).attr('src', url);
$(tmp).load(function(tmp) {
setTimeout(function() {
var bdy = tmp.contentDocument.body;
callback(bdy);
$(tmp).remove();
}, '100');
});
Since setTimeout() depends on the client's end, I would like to know if there is any better way to achieve the same goal. Thanks.
Check this question out, along with its many answers and related questions.
Update; here's some code that waits for #bar
to get loaded:
function f(callback) {
var tmp = document.createElement('iframe'),
$tmp = $(tmp);
$tmp.hide()
.insertAfter($('foo'))
.attr('src', url);
$tmp.load(function() {
var bdy = tmp.contentDocument.body,
$bdy = $(bdy); // small optimization
var waitForBar = function() {
if($bdy.find('#bar').length > 0) {
callback(bdy);
$tmp.remove();
} else
setTimeout(waitForBar, 50);
};
waitForBar();
});
}
精彩评论