Image preloading ... the fastest way - javascript

I'm working on a project dealing with a high traffic webpage (really high!). On landing page tons of images are displayed (~40), that needs to be there, right after the page was loaded to display them by fading in. We don't use any library for this since it should be loaded before it was ready to use. We have 4 image servers. Does anybody have any experience which is the best way to load images? I tried the following:
In page header, right after the <head>, inserted a script tag:
<script>
var img = new Image(); img.src= "src of the image";
</script>
Doing so, images begin and finish to load before DOMReady and Load event. But images on the page with the same url seem to load again, even if they was loaded before. The urls are the same, caching was on, Mozilla was used.
Maybe there's some mechanism that prevents the browser to use those images? or what?
Another question: does it cause any slowdown, when DOM and images load parallel?

First, I would recommend using CSS sprites. You can find more information here:
http://www.alistapart.com/articles/sprites
Second, if you want to load the images on DOM ready, use the following:
function listen(event, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(event, func, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + event, func);
}
}
listen('load', window, function() {
var img = new Image();
img.src= "src of the image";
});
Using sprites will cut your loading time in half. You eliminate the majority of your HTTP requests and the sprite sheets get cached right away so each subsequent page a user visits will already have it loaded.
EDIT
Here's a way to preload many images:
function preload(images) {
if (document.images) {
var imageArray = [];
imageArray = images.split(',');
var imageObj = new Image();
for (var i = 0; i < imageArray.length; i += 1) {
imageObj.src = imageArray[i];
}
}
}
Call the function like this:
preload('image1.jpg,image2.jpg,image3.jpg');

Related

Print arbitrary set of images at runtime with jquery/javascript

Let's assume a bunch of images are preloaded via something like this:
function loadNextImage() {
var img = new Image();
img.src = '/path/to/imageN.jpg';
img.onload = function() {
if(stillLoading()) {
loadNextImage();
} else {
printLoadedImages();
}
}
}
What can be used for printLoadedImages() to make them print (ultimately as a series- one per page, but for starters let's just say one image)
When I try setting the image source to a div, I can see the image- but trying printThis or printArea jquery plugins did not do it... seems to expect that the image was loaded via page load, not at runtime

How do I make .load() wait till everything is fully loaded? [duplicate]

I have a Python script that is doing some manipulation on a JPEG image. I pass some parameters to this script and call it from my HTML page. The script returns an img src="newimage.jpg tag.
I know how to wait for the reply from the script but I don't know how to tell when the image is fully loaded (when it is, I want to display it). What I get now is the image loading slowly so the user is seeing this "loading" process. Instead, I want to have a msg telling the user to wait while the image is loading, only then I want to display the image.
You can dynamically create a new image, bind something to its load event, and set the source:
$('<img>').bind('load', function() {
$(this).appendTo('body');
}).attr('src', image_source);
Image Loading
Wait for ajaxRequest
The other answers have mentioned how to do so with jQuery, but regardless of library that you use, ultimately you will be tying into the load event of the image.
Without a library, you could do something like this:
var el = document.getElementById('ImgLocation');
var img = document.createElement('img');
img.onload = function() {
this.style.display = 'block';
}
img.src = '/path/to/image.jpg';
img.style.display = 'none';
el.appendChild(img);

can we push images to browser cache using javascript

We have a print functionality in our application where we are printing images in the browser. We are dynamically forming the HTML div with all the image sources [image source is from the webservice url]
When we trigger 'Windows.Print()' , only the first image is always available in print preview (chrome) and remaining images are displayed blank.
If i trigger the print event for the second time, all the images are getting printed without any issue because all the images are cached by that time.
Please let me know how to push all my images in cache before printing. I need to do this in javascript. Dont want to make any html change.
I am using backbone.js and creating a model view with the images. Then Binding the view in HTML. Then i ma using for printing. This works fine in IE and Safari. but not in chrome, it shows print preview screen and always trying to load all the images from browser cache. But i will not be having those images in the browser while giving printing. All my images sources are dynamic and coming from the service. I am just setting the url dynamically to the image source.
<%_.each( Documents, function(oDocument) {%>
<div class="images span1">
<img src="<%- oDocument.URL%>" width="98" height="70" />
</div>
<% });%>
in print preview only one image is coming rest all coming as dots. if i cancel the print and give print again all are coming fine.
Thanks,
Jeevitha
This can be done purely in JavaScript by using the Image object.
var cachedImage = new Image();
cachedImage.addEventListener('load', function () {
alert('Cached image loaded');
});
cachedImage.src = 'http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png';
I have created a working JSFIDDLE example showing this at http://jsfiddle.net/pwdst/wc1zrL0v/
The new images could be created in response to a user event, for example clicking on a button, or even scrolling past a certain position. If the image from the server has the proper cache headers, it will then be retained in the browser cache for later use in your print page.
You will be able to see the request in the "Network" tab of the Chrome dev tools, or by using the excellent Fiddler tool from Telerik. Successful load will also trigger the load event listener added in the code sample.
I have called the custom function with the array of images i want to cache. Used Jquery 'Deffered' to hold the next operation until all the images are loaded. This is working very fine
var $deferredimages = $.Deferred();
var items = []; // load all the images paths
PreloadImages(items, loadImageitem, function (){
$deferredimages.resolve();
})
function PreloadImages(items, preloadimages, allDone) {
var count = items.length;
// this callback counts down the things to do.
var pendingimages = function (items, i) {
count--;
if (0 == count) {
allDone(items);
}
};
for (var i = 0; i < items.length; i++) {
// 'do' each thing, and await callback.
preloadimages(items, i, pendingimages);
}
}
function loadImageitem(items, i, onComplete) {
var onLoad = function (e) {
e.target.removeEventListener("load", onLoad);
// this next line can be removed.
// only here to prove the image was loaded.
document.body.appendChild(e.target);
// notify that we're done.
onComplete(items, i);
}
var img = new Image();
img.addEventListener("load", onLoad, false);
img.src = items[i];
img.style.visibility = 'hidden';
}
Reference http://jsfiddle.net/8baGb/1/

Preloading images with javascript Image() elements sitewide in <head>?

I made a small preloading script to preload some mouseover icons in the footer of a website I was working on, but I was wondering, once a resource like an image is loaded, will it persist sitewide? I wanted to, once all other loading is done, work on preloading the images for the gallery page so when someone visits the gallery it doesn't have to load them on demand. If I write some javascript to preload all the images in a particular folder, will most browsers recognize that those resources are the same ones specified in another page? For instance if i do
var preloader = new Image();
preloader.src = "/wp-content/..../galleryimage1.jpg";
in the frontpages header, when they go to the gallery will it still have that image resource downloaded and recognize it as the same resource (assuming the browser cache hasn't been somehow cleared in between)?
EDIT: I expanded the script to recurse the upload directories of the site (it's wordpress) and load images after the page is loaded
jQuery(window).load(function(){
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
<?php
//recurse the directory structure of "uploads" to find all normal image files
$dash_Directory = new RecursiveDirectoryIterator("/path/to/wp-content/uploads/");
$dash_Iterator = new RecursiveIteratorIterator($dash_Directory);
$dash_Images = new RegexIterator($dash_Iterator, '/^.+\.(png|jpg|jpeg|gif)$/i', RecursiveRegexIterator::GET_MATCH);
$dash_js_image_list = "";
//build js object to be loaded into preload() on $(window).load which occurs after entire page has been loaded
foreach($dash_Images as $Image=>$object){
$dash_js_image_list .= '"'.$Image.'",'."\n\t\t\t\t\t\t\t";
}
//remove the last comma and indentations to preserve syntax in js
echo substr($dash_js_image_list,0,-9);
?>)
});
is this script safe? is it useful? what should I do?

Replace img src but have loading graphic display while image is downloading

I have a page that swaps some fairly large images in and out. There are too many to preload when the page initially loads so that is not an option. So what I need to do is load them as they are requested by the user. Right now I'm using jQuery to replace the img's src. This works fine but the images I am loading can be around 500KB and it looks bad as they paint down the screen as they are downloading. What I'd like to do is pop a loading gif on the page when the image is in the process of loading then have the loading gif disappear once the image is loaded. I'm struggling to find a way to do that though. Here is the JS/jQuery code that I have that just replaces the src.
var product = "bowl";
var image = "dog.jpg"; //this is actually pulled from a data attribute, but its just hardcoded here for an example
$("#images img[data-product="+product+"]").attr("src", "/img/tablesetting/"+image);
I made a working jsfiddle showing this principle
http://jsfiddle.net/kasperfish/c72RT/4/
I recently needed to do the same thing. Basically I wrapped the image in a container div. within the container I've added a span element with my ajax loader gif embedded. this span has to be hidden initially but gets visible when an ajax request is made. The span gets removed when the image is fully loaded.
before ajax call
$('#your_image_container').find('span').show();
on success
$('#your_image').attr('src', 'your/image/url').load(function() {
$('#your_image_container').find('span').fadeOut();
});
I made a jsfiddle showing this principle
http://jsfiddle.net/kasperfish/c72RT/4/
Preload the image.
var product = "bowl";
var imageSrc = "dog.jpg";
var imgEl = $("#images img[data-product="+product+"]");
// show loading graphic only if it's needed
var timer = setTimeout(function(){
imgEl.attr("src", "/img/loading.gif");
},50);
// preload image
var img = new Image();
img.onload = function() {
clearTimeout(timer);
imgEl.attr("src",imageSrc);
}
img.src = imageSrc;
$img.attr("src", newImage);
if (!$img.get(0).complete) {
$img
.hide()
.after("<img src=throbber>")
.on("load", function () {
$(this).show().next().remove();
});
}

Categories

Resources