How can I load an image before it's needed? - javascript

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];
}

Related

Lazysizes wait until image is fully loaded in background

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.

Do browsers lazy load hover images by default

It seems that Chrome lazy loads hover images only when they are needed. For example, an image for :hover is loaded only when a mouse is hovered over an element. Is this an expected behavior? Does it encompass all images or only those defined for pseudo classes? How do I force it to load all images once the page is loaded?
Chrome do not "preload" images which aren't actally shown and, being this a desiderable effect, all modern browser shouldnt't.
To "force" browser in having all image ready in the cache when needed you may follow different approuches:
1) Preload required images with Javascript, you can use something like this:
var prld = ["one.gif", "two.gif", "three.jpg", "..."];
var img = [];
for (i = 0; i < prld.length; i++) {
img[i] = new Image();
img[i].src = prld[i];
}
but you might written in different ways, of course, that's just a suggestion.
2) The second method has a different approach, it is based on the idea that with a classic Javascript preload you have anyway to make as many "calls" as the images actually are. So 10 images with preload produces 20 calls to the server... not really a desiderable thing cause the "delay" of the calls will slowup all the page load...
So we put more than one image into a single files (like a "puzzle") than we put images as a background (of an empty DIV for instance) passing a different positioning of the background trought CSS.
No need to build a unique file for ALL the images, for instance you would decide for building several mosaics of two images just for the preloading purpose; so the :hover will "replace" the background rather than make a substitution.
The technique is described here: http://www.w3schools.com/css/css_image_sprites.asp
Each of those metods has its downside, it depends on situation.
All in all, as a general consideretion, i'd avoid "hovering" at all, taking in account that, on mobile experience, is, basically, without meaning... and it would lead to additional efforts to avoid mobile "extraload" useless contens...
Use this to force preloading for all img
var prld = document.querySelectorAll('img');
var img = [];
for (i = 0; i < prld.length; i++) {
img[i] = new Image();
img[i].src = prld[i].src;
}
This does NOT include images which are set in a div as background for example.

Proper method for simple 'lazy loading' of images

I am building a web application that is extremely image heavy. A feature of it is an interactive timeline which allows the user to scroll through a series of years. Each year has a photo gallery with 20-50 images. I am looking for the best solution to hide images on load, and load them on demand (a click event). Here are a few options:
1) Use javascript to assign the data-src to the actual src on demand.
<img src="blank.png" data-src="images/real-image.jpg">
2) Place all images inside a div with display:none. I believe some browsers still load these images on load, so might not be a good idea
<div style="display:none">
<img src="images/real-image.jpg">
</div>
3) Use a technique like lazyload. This plug, JAIL allows for images to be loaded after an event is triggered.
Thanks in advance!
Number one is good. Just but let src point to nowhere src=""or to a single placeholder image. If you need the image file, switch src with the real path, and the Browser loads it. Switch again for removal, then the file is fair game for the gargabe collector.
Number two will just hide but still load the image.
Number three basically does what Number one does.
(First post, no reputation, still hope I can help).
I use the following technique:
// Contains Image path strings that can be loaded statically or dynamically
var imgs = [img1, img2, img3, img4];
var img = new Image();
img.style.cssText = "position: absolute; visibility: hidden; display: block";
document.body.appendChild(img);
for (var i = 0 ; i < imgs.length ; i++)
img.src = imgs[i];
Each iteration posts an HTTP request for the image, which is later cached upon arrival.
This works for me. I load the string paths into the HTML using a server-side generation.

Add Transparent Image on top of other Images with JavaScript

I need to add a Transparent image on top of all images on a page. The goal is if a user were to do a simple right click and save of an image, they would save the transparent image.
I do realize this is not a guaranteed method and that none exist to prevent image theft but simply a measure that a client wants added to prevent your average non tech person from saving images.
Using JavaScript I would like to find all images or all images within a certain Div.
Apply a new image overlay on top of these images that will have the same width and height of the image they are covering
I am not sure how to do this with JavaScript and was hoping someone would have a quick fix or example. I was unable to find anything so far on Google or SO. Appreciate any help
I have this JS which gets all images on a page so far...
// Get all images on a Page
function checkimages() {
var images = document.images;
for (var i=0; i<images.length; i++){
var img =images[i].src;
// Add new transparent image on top of this image
alert(img);
}
}
I would advise you to work with jQuery (or similar library) to keep things easier. I would even write a small jquery extension to make it easy to recycle the code, and apply it on any div (or other wrapper), wich child images you want to be overlayed.
My code would look something like this:
// jquery plugin to create overlays
// src is the url of the overlay image
// apply to any container that contains images to be overlayed
$.fn.overlayImages = function(src) {
// loop trough the images
$(this).find('img').each(function() {
// cache some variables
var $img = $(this);
var $parent = $img.parent();
// make the parent relative, if not yet absolute or fixed, for easy positioning
if ($parent.css('position') !== 'fixed' && $parent.css('position') !== 'absolute') {
$parent.css('position', 'relative');
}
// get the position of the image
var position = $img.position();
// clone the image
var $overlay = $img.clone();
// set the styling, based on the img, for exact positioning
$overlay.css({
top: position.top,
left: position.left,
position: 'absolute',
width: $img.width(),
height: $img.height()
});
// change the src attribute for the overlay
$overlay.attr('src', src);
// insert the overlay to the DOM
$overlay.insertAfter($img);
});
}
// when the DOM is loaded (not just ready, the images need to be there to copy their position and size)
$(window).load(function() {
// apply the overlay plugin to the wrapper of the images
$('#replace-images').overlayImages("http://www.riptideinnovations.com/images/watermark.png");
});
I added the step by step explanation inside the code as comments, but do feel free to ask if you want any further explanation.
I set up a small fiddle to demonstrate: http://jsfiddle.net/pP96f/6/
I don't know if this would help, but you could make your images all div's with backgrounds like this:
<div style="background-image: url('<your_image>');"></div>

Sizing/stretching images to dimensions known only after page load

On my website, users can upload large images. I display these images like this:
<img id="userImage" src="userImage.ashx?width=740&id=4fc265d4-a83c-4069-8d6d-0fc78ae2840d">
userImage.ashx is a handler that returns image files based on id, so in this example the image for user 4fc265d4-a83c-4069-8d6d-0fc78ae2840d is returned. You can also set other attributes - in this example only width is given. The image is resized so that it is 740px wide.
I set the src of the image in javascript, once the rest of the page has loaded. By doing this I know how wide the image has to be to fill all the available space:
var width = document.getElementById("userImageHolder").getComputedSize().width;
document.getElementById("userImage").src = "flash/userImage.ashx?type=micrositePhoto&id=" + userId + "&width=" + width;
This all works, but the image doesn't load until everything else on the page has loaded. I have a complex solution to a simple problem.
Is there a better way to do this? What is the best way to shrink/stretch images to fill an area that is only known once the page loads?
Figure out what the upper limit is for width and height and generate the image to that size, then use max-width/max-height to allow the browser to auto scale it based on the size of the browser window.
Try to preload your images in a onDOMReady handler, and then insert in an onLoad one. While this can't guarantee the images to be loaded before everything else, they can at least start loading earlier.
Someting like this (using jQuery):
$(document).ready(function(){
var imageArray = [],
imageSrc = [];
//Fill image src array from somewhere
var len = imageSrc.length;
for(var i = 0; i < len; i++){
var img = new Image();
img.src = imageSrc[i];
img.onload = function(){
//Do something with your loaded image
imageArray.push(this);
}
}
});

Categories

Resources