Preload preview images before appending them to DOM

This commit is contained in:
Pavel Djundik 2017-12-29 12:30:15 +02:00
parent 49135f4d77
commit e98291dd3f

View File

@ -15,6 +15,19 @@ function renderPreview(preview, msg) {
return; return;
} }
const template = $(templates.msg_preview({preview: preview}));
const image = template.find("img:first");
if (image.length === 0) {
return appendPreview(preview, msg, template);
}
// If there is an image in preview, wait for it to load before appending it to DOM
// This is done to prevent problems keeping scroll to the bottom while images load
image.on("load", () => appendPreview(preview, msg, template));
}
function appendPreview(preview, msg, template) {
const escapedLink = preview.link.replace(/["\\]/g, "\\$&"); const escapedLink = preview.link.replace(/["\\]/g, "\\$&");
const previewContainer = msg.find(`.preview[data-url="${escapedLink}"]`); const previewContainer = msg.find(`.preview[data-url="${escapedLink}"]`);
@ -33,23 +46,13 @@ function renderPreview(preview, msg) {
const channelId = container.closest(".chan").data("id") || -1; const channelId = container.closest(".chan").data("id") || -1;
const activeChannelId = chat.find(".chan.active").data("id") || -2; const activeChannelId = chat.find(".chan.active").data("id") || -2;
let bottom = false;
if (activeChannelId === channelId) {
bottom = container.isScrollBottom();
}
msg.find(`.text a[href="${escapedLink}"]`) msg.find(`.text a[href="${escapedLink}"]`)
.first() .first()
.after(templates.msg_preview_toggle({preview: preview}).trim()); .after(templates.msg_preview_toggle({preview: preview}).trim());
previewContainer previewContainer.append(template);
.append(templates.msg_preview({preview: preview}));
if (activeChannelId === channelId) { if (activeChannelId === channelId) {
if (preview.shown && bottom) {
handleImageInPreview(msg.find(".toggle-content"), container);
}
container.trigger("keepToBottom"); container.trigger("keepToBottom");
} }
} }
@ -61,10 +64,6 @@ $("#chat").on("click", ".text .toggle-button", function() {
.find(`.preview[data-url="${self.data("url")}"] .toggle-content`); .find(`.preview[data-url="${self.data("url")}"] .toggle-content`);
const bottom = container.isScrollBottom(); const bottom = container.isScrollBottom();
if (bottom && !content.hasClass("show")) {
handleImageInPreview(content, container);
}
self.toggleClass("opened"); self.toggleClass("opened");
content.toggleClass("show"); content.toggleClass("show");
@ -84,17 +83,6 @@ $("#chat").on("click", ".text .toggle-button", function() {
} }
}); });
function handleImageInPreview(content, container) {
const img = content.find("img");
// Trigger scroll logic after the image loads
if (img.length && !img.width()) {
img.on("load", function() {
container.trigger("keepToBottom");
});
}
}
/* Image viewer */ /* Image viewer */
const imageViewer = $("#image-viewer"); const imageViewer = $("#image-viewer");