fix: Handle broken images

This commit is contained in:
Faris Ansari 2019-02-20 19:01:51 +05:30
parent 126f8ce8f2
commit 41a4ba45da
2 changed files with 25 additions and 0 deletions

View file

@ -101,3 +101,8 @@ img {
height: 300px;
background-color: $light;
}
.broken-image {
padding: 50% 0;
background-color: $light;
}

View file

@ -330,6 +330,24 @@ $.extend(frappe, {
add_switch_to_desk: function() {
$('.switch-to-desk').removeClass('hidden');
},
setup_404_images: function() {
function image_exists(src) {
return new Promise(resolve => {
var img = new Image();
img.onload = () => resolve(true);
img.onerror = () => resolve(false);
img.src = src;
})
}
$('img').each((_, img) => {
image_exists(img.src)
.then(exists => {
if (!exists) {
$(img).replaceWith('<div class="broken-image">');
}
});
})
},
setup_lazy_images: function() {
// Use IntersectionObserver to only load images that are visible in the viewport
// Fallback for browsers that don't support it
@ -343,6 +361,7 @@ $.extend(frappe, {
.map(key => `${key}="${attrs[key]}"`)
.join(' ');
$target.replaceWith(`<img ${data_string}>`);
frappe.setup_404_images();
}
if (!window.IntersectionObserver) {
@ -424,6 +443,7 @@ $(document).ready(function() {
frappe.render_user();
frappe.setup_lazy_images();
frappe.setup_404_images();
$(document).trigger("page-change");
});