Preload may not be the correct term...
I have a page which loads a very large image. I wanted to wait for the large image to completly load before displaying on the page for the user.
At the moment, I have a loading gif and i'm using javascript to wait for the image to load and then replace the loading gif src with the image:
<img src="loading.gif" id="image" />
<script>
img = 'very_large_image.jpg';
var newimg = new Image();
newimg.src = img;
newimg.onload = function(){
$('#image').attr('src',img);
}
</script>
I'm wondering if there are quicker ways to load this image such as a pure CSS way or some way to force the browser to download this asset first. The code above is obviously positioned in the location where the image is expected to load. So there is code above and below.
One CSS option I thought was to position the image off the screen and once it's loaded, perform the src replace.
My server is running http2, so it should be pretty quick. I just want to know if there is a better way then what i'm doing now to ensure the large image is loaded the quickest way possible for all major browsers.
I should add, i've already done plenty of optimisation of the image file already. I'm working with high resolution photography.
Thanks!
You can make the JPG progressive and then just let it load. Browsers will progressively display the image first blurry and then load more details.
This is the best way because user can see the image even before it's fully loaded.
Edit:
On linux use jpegtran, on Windows use Photoshop or RIOT
Your doing a great job!
Here is what I came up with:
https://jsfiddle.net/Vandeplas/jkwweh52/
HTML:
<img src="http://loadinggif.com/images/image-selection/32.gif" large-src="http://www.planwallpaper.com/static/images/518079-background-hd.jpg" large-class="fancyImg">
JS:
$('img[large-src]').each(function() {
var img = $(this);
var newimg = new Image();
newimg.src = img.attr('large-src');
newimg.setAttribute('class', img.attr('large-class'));
newimg.onload = function() {
img.replaceWith(newimg);
};
});
That separates the JS from the HTML + you can easily add infinite more pre-loading images without having to change the js!
Very easy way to preload images which are needed later
$.preloadImages = function() {
for (var i = 0; i < arguments.length; i++) {
$("<img />").attr("src", arguments[i]);
}
}
$.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
I think that the best solution for your problem is split this image and load the parts assync at the same time
Related
I want to asynchronously download image, so first user sees a low resolution image, and higher resolution version is downloaded in the background. I have tried the following.
<html>
<head>
<script>
window.addEventListener('load', function () {
var kuvaEl = document.getElementById('kuva');
var r_src = kuvaEl.getAttribute('r-src');
var a_src = kuvaEl.getAttribute('a-src');
kuvaEl.setAttribute('src', r_src);
kuvaEl.setAttribute('src', a_src);
});
</script>
</head>
<body>
<img id="kuva" src="http://www.viikonloppu.com/wp-content/uploads/2014/04/lotoflaughters.com_-619x428.jpg?c3bc1b"
a-src="https://www.manitowoccranes.com/~/media/Images/news/2014/Potain-China-hi-res.jpg"
r-src="http://fuzyll.com/images/2016/angel_oak_panorama.jpg" />
</body>
</html>
But the problem is r_src download is aborted when src is change second time. I want to download both of these images in parallel, and show the r_src first (only if it downloads faster than a_src), and when the *a_src *is ready, show the a_src.
Also, is it possible to download these a_src and r_src images to the browser cache before the src is actually changed? Ideally I would like the the src change to either retrieve the image from the cache or join the pending download for that url.
I can also use jQuery. IE7 must support the implementation.
You just need to use javascript or jquery and load two version of the same image. the first will be your low res, but you will download a high res inside an hidden img tag.
When the download is complete, you just hide / delete the low res image and show the high res.
This link show some test and few way to do it. And it should support ie7 Load a low-res background image first, then a high-res one
You can use interlaced progressive JPEG format.
This method is the preferred method for handling high quality images and has been implemented by so many websites.the idea is that the compression of the image is made in such away that the when you send the image the receiver gets the image in finer and finer detail has the sending of the data progressed.
if you dont want to use the abouve technique
Have the low quality image in the src of the image. once the whole page loaded successfully,change the low quality image with high quality image
<img id="target-image" src="low-quality.jpg" data-src="high-quality.jpg" />
$(window).load(function(){
var imgSrc = $('#target-image').data('src');
$('#target-image').attr('src',imgSrc);
});
You should put your low res as default src. Then use JS to download the high res version and on download completion, change image src.
Also, good practice is to use data-* for custom attributes
If your really want a parallel download, you should replace "load" event for the "DOMContentLoaded" event. However, this will extend the time your user has to wait until page is ready. Your should keep the load event to prioritize critical assets loading (scripts and stylesheets)
window.addEventListener('load', function() {
// get all images
let images = document.getElementsByClassName("toHighRes");
// for each images, do the background loading
for (let i = 0; i < images.length; i++) {
InitHighResLoading(images[i]);
}
});
function InitHighResLoading(image) {
let hrSrc = image.dataset["hr"];
let img = new Image();
img.onload = () => {
// callback when image is loaded
image.src = hrSrc;
}
// launch download
img.src = hrSrc;
}
img {
/* only for code snippet */
max-height: 300px;
}
<img class="toHighRes"
data-hr="https://www.manitowoccranes.com/~/media/Images/news/2014/Potain-China-hi-res.jpg"
src="http://fuzyll.com/images/2016/angel_oak_panorama.jpg" />
I want to load two images in a single <img /> tag. First small image will be shown by src attribute and second large image will be inside data-src attribute but one image will be shown at once, that will be in src attribute. I want when page load small image will be load and show first and after completing loading of large image in the background it will be replaced by small image so that we can see large image. I have the code that will take large image from data-src attribute and place large image in src attribute.
$(document).ready(function(){
$("#image4").load(function(){
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
} }
});
});
I want to do this because I don't want to wait for long time to load large image, instead I want to see the small image first. I am facing the problem when page load, it's loading small and large images in parallel. For your information images have the drag and zoom functionality.
Current live code is here: http://virtualepark.com/new1/demo.html
The code you posted here is not deployed on your server - there is some other stuff using the mousewheel-event.
Try loading the big image hidden in the background and once its loaded, set the url of the visible image:
//get all images
$('img').each(function(i, img) {
var img = $(img);
//if they have a data-src
if(img.attr('data-src')) {
//register for the load-event for the initial image
img.one('load', function() {
//if small image is loaded, begin loading the big image
//create new hidden image
var hiddenImg = new Image();
hiddenImg.onload = function() {
//if the hidden image is loaded, set the src-attribute of the
//real image (it will show instantly)
img.attr('src', img.attr('data-src'));
};
//trigger loading of the resource
hiddenImg.src = img.attr('data-src');
});
});
});
(credits to Load image from url and draw to HTML5 Canvas)
you can load to hidden tag and after load complet change them.
you can try to start the loading after the image is loaded.
$('img').load(function(){
var bigImgSrc = $(this).data('src');
var img = $(this);
if(bigImgSrc != img.prop('src')){
var bigImg =$('<img>').prop('src', bigImgSrc);
bigImg.load(function(){
img.prop('src', bigImgSrc);
});
}
});
I'm not 100% sure if you need to append the bigImg to the DOM or if it also loads like this. If you need to add it to the DOM use bigImg.hide().appendTo('body') and then use the remove funtion when loaded.
You should also be aware that the load-function not work in all cases, see https://api.jquery.com/load-event/
edit there was in an infinity loop in the prev. code example
I'm using document.images to load images when a visitor first visits the website. The reason is because I have a few different areas which have rollover images. Before I switch over to using CSS sprites (modifying a lot of work), I'm going to ask here.
So I'm preloading images with this:
images = new Array();
if (document.images) {
images.push(preloadImage("http://website.com/images/myimg.png", 300, 200));
}
function preloadImage(src, x, y) {
var img = new Image(x, y);
img.src = src;
return img;
}
And according to Chrome's "resource" panel, this is working just fine. Even after pressing CTRL+F5, the images listed in the JS are downloaded.
HOWEVER, they are not used. If I hover over an element in one of my three scripts, the image is downloaded a second time. Derp?
I assume that when preloading images this way, you're supposed to put that image array to use. I thought the browser would be smart enough to say "Hey, this is the same image, let's use it twice" but apparently not.
So is this correct? Do I need to rewrite my programs to preload images individually? I know it doesn't sound hard, but it's really not designed for that.
This is not really an answer to your question, but I proprose a different solution. Put all the images you need to preload inside a div that is hidden from the user. I know, I know, this i not as elegant, but it should work just fine. :)
<div style="display: none;">
<img src="http://website.com/images/myimg.png" alt=""/>
...
</div>
This works fine for me:
function imgPreload() {
var imageList = [
"my/firstimage.png",
"my/secondimage.jpg",
"my/thirdimage.png"
];
for (var i = 0; i < imageList.length; i++ ) {
var imageObject = new Image();
imageObject.src = imageList[i];
}
}
imgPreload();
Cheers. Frank
Scenario
I use two images namely 'car-light.png' and 'car-dark.png'. When user touches the image, which was car-light.png, it becomes car-dark.png.
Here is the code I used.
<img src="car-light.png" id="car" ontouchstart="changeCar()">
In changeCar(), I wrote this code
$("#car").attr('src','url(car-dark.png)');
Question
Is there a way to speed this up by preloading the image? Or am I making too big a deal with fast loading time? If it is the case where pre-loading is necessary, is the following code correct?
var img1 = new Image();
img1.src = "car-dark.png";
function changeCar(imgName)
{
document[imgName] = img1;
}
and in HTML
<img src="car-light.png" name="car" ontouchstart="changeCar('car')">
Putting this somewhere in your startup JS code will preload the image:
var img1 = new Image();
img1.src = "car-dark.png";
This will cause the image to be in the browser cache so it will load quickly if you use it later on in the action of the page. You could use the img1 object directly, but often it's easier to just use the URL and let the browser fetch the image from it's memory cache like this:
<img src="car-light.png" id="car" ontouchstart="changeCar()">
function changeCar() {
$("#car").attr('src','car-dark.png');
}
Is there any way without AJAX of changing the loading order of images on a page? Or even a way to completely halt or pause loading of images already present?
The use case is simple - I have a long list of images down a page, and visitors will be landing on different spots of the page using URL anchors (/images#middle-of-page) that refer to actual containers for those images.
I'd like in the least to load the images inside the requested container FIRST, then continue loading the rest of the images.
The challenge is that there is no way to know the image paths of the requested container image before loading the page DOM.
I've tried getting the container img contents on load, then using the Javascript new Image() technique, but it doesn't change the fact that that image on the page will still be waiting for all previous images to load.
I've also tried immediately prepending a div in the body with a background image (CSS) of said img path, but this also does not prioritize the image load.
Any other ideas?
You need to have a DOM with empty img placeholders, i.e.
<img src="" mysrc="[real image url here]" />
Or you can make images to display "Loading..." image by default. You can even cache real image url in some custom tag, mysrc for example. Then once you know what exactly images you want to show (and in what order) you need to build a sequence of image loading
var images = [];//array of images to show from start and in proper order
function step(i){
var img = images[i++];
img.onload = function(){
step(i);
}
img.src = "[some url here]"
}
Hope this helps.
For interest, this is the function I ended up implementing based on the answers here (I made it an on-demand loading function for optimum speed):
function loadImage(img) { // NEED ALTERNATE METHOD FOR USERS w/o JAVASCRIPT! Otherwise, they won't see any images.
//var img = new Image(); // Use only if constructing new <img> element
var src = img.attr('alt'); // Find stored img path in 'alt' element
if(src != 'loaded') {
img
.load(function() {
$(this).css('visibility','visible').hide().fadeIn(200); // Hide image until loaded, then fade in
$(this).parents('div:first').css('background','none'); // Remove background ajax spinner
$(this).attr('alt', 'loaded'); // Skip this function next time
// alert('Done loading!');
})
.error(function() {
alert("Couldn't load image! Please contact an administrator.");
$(this).parents('div:first').find("a").prepend("<p>We couldn't find the image, but you can try clicking here to view the image(s).</p>");
$(this).parents('div:first').css('background','none');
})
.attr('src', src);
}
}
The img loading="lazy" attribute now provides a great way to implement this.
With it, images load automatically only when on the viewport. But you can also force them to load by setting in the JavaScript:
document.getElementById('myimg').loading = 'eager';
I have provided a full runnable example at: How do you make images load lazily only when they are in the viewport?
One really cool thing about this method is that it is fully SEO friendly, since the src= attribute contains the image source as usual, see also: Lazy image loading with semantic markup