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
function 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.