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

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?

Related

How to reload an image once it failed to load using jquery?

When loading large amount of images at once, every once in a while a few of them fail to load. If i visit the link of the failed image on a new tab, it loads up back where it failed to load, maybe from cache but i am not sure. I found the code below which detects if an image has loaded or failed, i tried to make it so it reloads the image once its failed but it does not work. Would there be any way to make the code work so it keeps reloading the image until it loads once it fails to load?
var $posts = $(this.responseText); //ajax response
$posts.find(".icon").each(function() {
var url = $(this).attr("data-src")
var reload = $(this).attr("data-src")
testImage(url)
function testImage(url) {
var tester = new Image();
tester.onerror = imageNotFound;
tester.src = url;
}
function imageNotFound() {
var img = new Image();
img.src = reload
console.log("reloaded")
$(this).Lazy({
effect: 'fadeIn',
effectTime: 500,
visibleOnly: true
});
}
In the code i use data-src instead of src because i am using the lazyloading plugin, i re-initialize the plugin on the link once the function is called, if i disable the lazy loading plugin and only use the src of the image it makes no difference.

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/

Image preloading ... the fastest way

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');

Do not load images in javascript

I build a website and i want to ask the user when each time visit the site, if he want to display images or not. and if not, i want to do not load them and display the page without any img tag
i tried this, but this is not useful because the page will be loaded
function load_img () {
if (!confirm("Do you want to load the images on your site?")) {
var images = document.getElementsByTagName("img");
var l = images.length;
for (var i=0; i<l; i++) {
images[0].parentNode.removeChild(images[0]);
}
}
}
i need some code that don't load any img tag when the page load,
and not a code that hide or remove the images after the page is loaded and the images are displayed
can someone help me please with this javascript code
thank you
You can take a look at lazyload plugin for jQuery. What this plugin does is load the image when the image is on the visible area of the page.
Their idea is to put the original URL to the image in data-original attribute and in the src attribute put some small image e.g. 1x1 transparent gif like this:
<img data-original=“img/example.jpg” src=“img/grey.gif” />
and then you are able to load all the images whenever you want to just by replacing the the src.
this is a simple javascript code that you can try:
window.onload = function() {
if( confirm('Images?') ) {
var img = document.getElementsByTagName('img');
for(i in img) {
var original = img[i].getAttribute('data-original');
if( original.length ) {
img[i].setAttribute('src', original);
}
}
}
}
You could try jquery : $("img").remove();
It would be better to solve this problem from the server side!
Make start page with a link to a version of the page with images and one without the images. You can write a server side script (PHP?) to show or hide the images. Simple removing the images could break the page design. Also removing html image tags does not do the trick. What about background images, some in css files, ...
If you like to do this an on the client side with javascript you have to remove all images and add them manually with javascript.
Using jQuery you can do:
if (confirm('Hide images?'))
{
$('img').remove();
}
Without jQuery you have to use getElemtentsByTag and a loop.

Caching dynamically loaded images

I'm using javascript to dynamically load any of a series of images into a single img tag, based on user interaction:
function reassignImage(newSource)
{
img.src = newSource;
}
This works great, except that I when I inspect it with Chrome developer tools,
I see that even if I reload an image I've already loaded, it makes another http call AND grows the total Images Size graph.
This seems like the worst of both worlds. I would want either:
To load from cache if the image were
the same.
To reload each image
everytime, but then not grow the
cache.
How would I achieve either scenario?
Thanks! Yarin
What's the cache-control header set to in the http response for the image? (Chrome developer tools will show you). If it's not set to be cacheable, it will get refetched.
This will pre-load an image so that the browser can display it immediately when you actually set the src of an img tag. I speculate that pre-loading an image like this will ensure it's in the cache so it won't reload, though I haven't tested it.
var myImg = new Image(25, 25);
myImg.src = "/foobar.png";
In other words, this should now hopefully only download two images
function reassignImage(newSource) {
var myImg = new Image(25, 25);
myImg.src = newSource;
img.src = newSource;
}
reassignImage("first.png");
reassignImage("second.png");
reassignImage("first.png");
Edit
I was doing it wrong. Try creating a new Image() for every new file the user loads. Swap these image elements in and out of the dom.
<html>
<head>
<script>
var imageElements = {};
function reassignImage(newSource) {
if (typeof imageElements[newSource] == "undefined") {
imageElements[newSource] = new Image();
imageElements[newSource].src = newSource;
}
var container = document.getElementById("imageContainer");
container.innerHTML = '';
container.appendChild(imageElements[newSource]);
}
</script>
</head>
<body>
<div id="imageContainer"></div>
</body>
</html>
Technically you can set it this way in .htaccess file:
# Set up caching on images for 1 month
<FilesMatch "\.(jpg|jpeg|png|ico|gif)$">
ExpiresDefault A2419200
</FilesMatch>
If you would like with this settings force image to refresh, append this to its URL:
'?'+ new Date().getTime()

Categories

Resources