On a complex AJAX site I need to retrieve CSS-dimensions of newly inserted DOM objects, i.e. the value of a certain DIVs innerWidth, so I can resize loaded images to their parents dimensions.
I am loading the new Stuff into the DOM via jQuery.load()-POST:
$( 'DIV#newStuff' ).load( 'insertthis.ajax', {id:1}, function() {
var iMaxWidth = $( 'DIV#widthNeeded' ).innerWidth();
console.log(iMaxWidth);
} );
The problem: FireFox (PaleMoon) 9.2 => returning “442” as expected.
Maxthon 3 and Chrome 17 => returning either “0” or a much higher value “736”.
Both on Win7. jQuery 1.7.1
I also tried the jQuery.actual()-plugin with the same results.
To clearify: this is a very much simplified extract of the actual function. I’m only trying to show the core problem. The loaded script is plain PHP (I changed the extension to .ajax).
The solution (workaround):
Wrapping the success callback code with an additional setTimeout()-function gives some browsers the dire needed time to calculate the newly rendered DOM-stuff’s dimensions proberly.
$( 'DIV#newStuff' ).load( 'insertthis.ajax', {id:1}, function() {
setTimeout( function() {
var iMaxWidth = $( 'DIV#widthNeeded' ).innerWidth();
console.log(iMaxWidth);
}, 500 );
} );
Answering your revised question:
I can’t immediately see why you’d be getting those kinds of discrepancies. It may be that you need to give the browser a moment to reflow or something, by effectively doing a yield, like this:
jQuery calls the
loadcallback immediately after updating the element. I’ve sometimes seen browsers need you to give their rendering thread a moment to reflow.