I'm working on a project that needs to automatically load content and insert it at the beginning of a page without disturbing the page's vertical scroll position. Inserting the content, calculating its height, and then adding that to the page's scroll position has worked for me so far, but now I'm encountering issues where it doesn't get the correct height if there are images (presumably because those images haven't loaded yet). How can I load the images before inserting the content into the page, so that it calculates the correct height upon insertion? Or is there an even better way to go about doing this?
Some (simplified) code for reference:
$.ajax({
type: "POST",
url: post_url,
dataType: "json",
data: post_data,
success: function(data, stat, jqXHR) {
if (data.content.length) {
var updates = build_content(data.content);
$(updates).insertAfter("#" + id + " .reload_button");
// Works if there's no external content
$("#" + id).scrollTop($("#" + id).scrollTop() + $(updates).height());
}
}
});
Update: I've tried using .load() to wait until the content as fully loaded:
(...)
var updates = build_posts(data.response.posts).hide();
$(updates).insertAfter("#" + id + " .reload_button");
console.log("Waiting for DOM to load completely @ " + new Date().getTime());
updates.ready(function() {
console.log("Done @ " + new Date().getTime());
$(updates).show();
(...)
It was apparently loaded the same millisecond that it inserted the content, which can't be right since it had to load an image as well. Am I making an obvious mistake here?
Update: using .load instead of .ready just causes the callback function never to run at all. The documentation says that it's buggy and might not be called if the images were cached by the browser, but I don't know if this is really what's happening.
I ultimately solved this with Alexander Dickson's waitForImages jQuery plugin. I don't know why .load() refused to work, but so far this plugin has had no issues, so I'm sticking with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With