I am using lazysizes for lazy image loading. It's working fine, but I was asking myself if it is possible to load the images in the background and replace the src attribute after the real image is fully loaded.
The problem I am facing right now is, that the src attribute is replaced with the real image when visible, but on slow internet connections, the image slowly loads from top to bottom.
I would rather wait until the image has loaded in the background and then replace the src attribute to prevent the effect shown in the screenshot below.
Do I have to use another library or can I arc hieve this with lazysizes?
Thanks in advance!
You can load an image with this code:
function loadImage(url, callback) {
var img = new Image();
img.onload = callback;
img.url = url;
}
Then on callback set your image url:
var url = "http://path.to/my/image.jpg";
loadImage(url, function() {
document.getElementById("myimg").src = url;
});
Answering my own question:
You can use the class .lazypreload to achieve this effect.
Related
I'm developing a website with an image gallery. There is a grid of images with dozens of thumbnails. When a user clicks on an image a div slides down from the top. That div's CSS gets edited with JavaScript to change the background-image.
My problem is that the div slides down, but the background image "flickers" in randomly. What I want is the div to slide down with the image already loaded. I'm not sure how to solve this problem because I think it would be unreasonable to pre-load every thumbnail's larger version when the user most likely won't click on them all.
You can convert the image to base64 and enable it in src of the img tag, after that send in the dormulário.
this use example: https://hdtuto.com/article/how-to-convert-image-into-base64-string-jquery
One way to preload images is to create an image object using javascript
Here's an example:
HTML:
<img src="photo1.jpg" id="photo" />
Javascript:
var photo = document.getElementById("photo");
var loadImage = new Image();
loadImage.src = "YourSrc/image.jpg";
Last step, use this code in your event handler when you want to change to the preloaded image:
photo.src = loadImage.src;
If you are looking to preload multiple images use an array and a loop.
imageSrcs = ["imgsrc1.jpg", "imgsrc2jpg", "imgsrc3jpg"];
preloadedImages = [];
for(var i = 0; i < imgSrcs.length; i++)
{
preloadedImages[i] = new Image();
preloadedImages[i].src = preloadedImages[i];
}
I am facing a bit of an issue and cant seem to find a solution. I have a section tag
<section class="background-gif"></section>
This simply loads a background image
.background-gif {
background: url(../images/image.gif) no-repeat top;
background-size: 100%;
}
Straightforward enough. Problem is, the gif that is being loaded is 5MB as it has a lot of animation. This is causing the page load to be mega slow. I can't use a standard preloader, to do with requirements.
Instead, I thought I would give something like this a go https://medium.com/front-end-hacking/how-to-optimize-image-loading-on-your-website-855020fb41ae
However, my IDE does not seem to like this code, I think it is ES6? So I essentially trying to do something similar. My thought is to replace the above CSS so it initially displays a static image. And then in the background, the gif can load, and once loaded, replace the static image.
I have seen examples where an Image Object is used, something like this Dynamically replace image src after the page loaded and the image is completely downloaded
I cant however find anything that does this with background images.
How would I go about replacing the static background once the main gif has fully loaded?
Thanks
By giving the section.background-gif a placeholder image(in your case it can be a minified image from the GIF image that you want to load) , and give it a data-src attribute containing the path/link of the desired GIF image, then using JavaScript we'll load the GIF image based on the data-src attribute of the section.background-gif element, and when it loads we'll assign its src attribute to the background-image property of the section.background-gif element.
Here's a runnable snippet to illustrate:
In the snippet, I'm using a placeholder image from placeholder.com website that initially appears as the background, then I load a random GIF image from Google. The snippet may not work as expected due to some restrictions(as the snippets are sandboxed), so try it in your project it should work, just don't forget to replace the image links with yours.
// referencing the section element, and creating a new Image object.
var section = document.getElementsByClassName('background-gif')[0],
img = new Image();
// assign the data-src to the img variable src.
img.src = section.getAttribute('data-src');
// adding a 'load' event listener in which will change the section's background image when the img is loaded.
img.addEventListener('load', function() {
// the img is loaded, assign its src attribute to the section.
section.style.backgroundImage = 'url("' + this.src + '"';
// just for testing, not required.
console.log('The image has been loaded.');
});
section {
/* just for the demo */
height: 100vh;
}
.background-gif {
/* change the url to your image link */
background: url("https://via.placeholder.com/350x350") no-repeat top;
background-size: 100%;
}
<!-- don't forget the data-src to point to the large GIF image you want to set as a background -->
<section class="background-gif" data-src="http://cosmicweb.uchicago.edu/images/mov/s02_0.gif"></section>
Hope I pushed you further.
You can try preloading images. Preloading an image as an object will allow for linked event listeners including "onload". Let's try this....
window.addEventListener('load',init);
function init(){
var image = new Image();
image.src = 'https://images.unsplash.com/photo-1530482817083-29ae4b92ff15?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=44f4aebbd1e1371d5bf7dc22016c5d29&auto=format&fit=crop&w=700&q=60';
image.addEventListener('load',function(){
alert('image loaded');
document.body.style.background = 'url('+image.src+') no-repeat top';
});
}
Let me know how it goes with a larger image. I'm curious.
Im changing the background image with the following code inside a script tag. This is causing a whiteflash when the background changes, all my pages are ajax. I cant just pick a background color like the background as im also using this on profiles page and each profile has a different background.
is it possible to preload the image then change the background to stop the whiteflash? thanks
$('body').css('background-image', 'url(../images/waves.jpg)');
$('body').css('background-attachment', 'fixed');
$('body').css('background-size', 'cover');
You could load a hidden image and change it when the image finishes loading, like this:
function preloadImage(source, destElem) {
var image = new Image();
image.src = source;
image.onload = function () {
var cssBackground = 'url(' + image.src + ')';
$(destElem).css('background-image', cssBackground);
};
}
Usage:
preloadImage('images/waves.jpg', 'body');
EDIT: Wrapped the code inside a function.
EDIT 2: Here is an example without the background flash while changing. http://jsbin.com/admmx/4/edit?html,css,js,output.
You can preluad image using Image() object.
var newImg = new Image();
newImg.src = "img2.jpg";
$('body').css('background-image', 'url('+ newImg.src +')');
I don't know if it would suit you, but I would use wrapper for the background and wrapper for the content. That way I can animate the change for my background without too much worry about the rest of the page.
If you know the pictures upfront you can use CSS classes to change them smoothly.
<body>
<div id="bg-wrapper" style="position: absolute; left: 0; top: 0"></div>
<div id="content-wrapper"></div>
</body>
of course I would write some code to look after re-sizing the browser window.
Here is an example fiddle
I am working on a web application in which user can navigate to the next and previous images one by one which are placed in some location in file system.
I am having facing a problem while image loading.When a high resolution image is loaded to container it flickers and then renders.I am using onload event to ensure that image is completely loaded in this way:
image.onload = function () {
$('#img').attr('src', image.src);
};
image.src = imagePath;
To give a better user experience i am trying to load a low resolution image first so that it display immediately and then it fade out then the higher resolution image fade in when it is completely loaded.Low resolution image renders immediately but the high resolution image still flickers and then displayed on container.It is not looking smooth on image change.
How can I resolve this issue? Please provide some solution or idea that i can implement for better user experience.
setTimeout(function() {
image.onload = function () {
$('#img').attr('src', image.src);
};
image.src = imagePath;
}, 5000);
you can use settimeout so that the flickering will not be visible to the user. This might not be the best solution. but it may fix ur issue
When I load an image object in the DOM for large images this will freeze the display for a moment on the iPad.
For testing purpose, let a GIF animation loader spin and add a large image to the DOM, when the image is loaded and added to the DOM you will notice that that GIF animation will freeze until the image is being displayed. This freeze will be enough to disable the CSS3 animation effect on it.
Is there something like
var image = new Image();
image.ready = function() { alert('the image is being displayed.') };
You can check if the image has been loaded like this
var img = new Image();
img.onload = function() {
alert('Done!');
}
img.src = '/images/myImage.jpg';
For preloading images on mobile web applications, I've had success using html5-preloader. It seems like this is something that might help you as well.
HTML5-Preloader