How to use javascript to preload images - javascript

I have looked at a number of SO questions on how to preload images, I have created a function
$(images).each(function () {
var img = new Image();
img.src = this;
$(img).appendTo('body').css('display', 'none');
});
Which appends the images to the dom. However when I add a product to my cart, (the minicart will contain the images which have been preloaded), chrome still produces a request on that minicart image even though it has been preloaded (I can see the image in chrome developer tools). How do I get chrome to use the image which has already been loaded instead of getting another one from the server?

your server is sending wrong headers; do a search about Cache-Control, Expires, Etag and Pragma and set them to cache your images instead of download
chrome is buggy or it intentionally downloads the image twice. for example setting display:none too early may cause the problem, use position:absolute;left:-100000px; instead
your developer tools is set to disable cache (click on the gear icon, then uncheck General > Disable cache (while DevTools is open) )

Related

Dynamically Loading Images not cached

I am trying to load an animated image on top of an element, and to do this I am switching between a list of pngs (labelled 1 - 124) and creating an image element for each of them and giving them a src.
The idea is I can have an empty image element and run a function to swap the src every 25 milliseconds with the next image in the list to give an animated image effect.
This works fine on Mac (chrome) as it loads the images ONCE and then seemlesly changes the src without loading any more images (I checked this by looking in the network tab of the chrome dev tools).
But for some reason on my windows PC it is sluggish and is trying to load the image from the server again every 25 miliseconds ..
cycle_images: function() {
this.imageCount = (this.imageCount < 123) ? this.imageCount + 1 : 0;
document.querySelector('.animated_image').html = this.imageList[this.imageCount];
},
This is the code I am using and I am confused why it works fine on my macbook but not my pc. Is there any way to force images to not re-load and just looad from cache?
One solution could be creating 124 img and make them invisible on the page and then change your image accordingly.
But a most promissing and proper way could be concatenating these image into one gif file and load it once! This way use internal engine to render and it is much more effecient and also does not affect on user experience.

Download a file when clicking an anchor in Internet Explorer

I've seen similar questions but so far am unable to solve this problem:
I am trying to download a file (mp4) located in Azure Blob storage when an anchor is clicked. This currently worked in Chrome, Firefox, Safari etc but from what I'm aware IE doesn't support the download attribute.
I have access to the storage account so tried changing the Content-Type to application/force-download and the Content-Disposition to attachment;filename=someName. This resolved the problem for Firefox cross domain limits but still no joy in IE. I have tried application/octet-stream but this did not work either.
Currently in IE11 it tries to open Windows Media Player (not sure why), but in IE10 and lower nothing happens, the browser just hangs whilst trying to navigate to the blob storage URL.
So next was to try some client side. Using Jquery I attempted the following:
$('.fallback[data-auto-download]').click(function () {
var $this = $(this);
window.location = $this.attr('href'); //download file
setTimeout(function () {
window.location.href = "/Content/Confirmation";
}, 3000); //redirect to new page after timeout
});
And this is how it looks in the markup:
<a class="fallback" data-auto-download href="http://someBlobURL">Download video</a>
As mentioned above this is not working for IE. Are there any current methods to get this to work? Research states to change the Content Type but that doesn't seem to get it working.
Please note: We cannot use right click to save target as because this project requires a new page to be loaded when the file download has been initiated.

How to cancel an image from loading

Suppose in Javascript that you assign the SRC to an IMG tag. It is a large SRC and you want to cancel it before it has finished loading. Assigning the SRC to another image will not stop the data from loading.
That is, in the middle of the load you can assign the SRC to another smaller image and the smaller image will be loaded and appear in your browser. However, the original SRC still continues downloading.
Similarly, deleting the IMG node will not prevent the SRC from continuing to download. No guesses please, look at the repro steps.
REPRO
Load this URL in Chrome in Windows: http://68.178.240.17/imgLoadTest/imgLoadTest.htm
Open up the developer panel by pressing CTRL-SHIFT-J
On the top row of icons in the Chrome developer panel click the Network icon to watch network activity.
On the web page loaded in Step 1 click the Load Image button and watch the developer panel as a large (32meg) image starts loading.
On the web page click the Try To Cancel button to load a different image.
A small image loads, but watch the network in the developer panel and notice that the large image continues to download.
Quick answer
Setting the src attribute of the img tag to the empty string will interrupt the current download, even on Chrome.
Details
Nowadays most of browsers implemented that out-of-standard mechanism thought in the old answer to programmatically abort the connection. This is not achieved through a protocol request, but with a client-side in-memory operation. Keep in mind that is not a standard behaviour, but most of vendors courtesy. That is, it could not work on every browser.
I've prepared a jsfiddle showing this mechanism in action (keep an eye at the network panel of the inspector).
Old answer (2011)
Your browser asks for that image with a specific HTTP GET request, as specified in HTTP protocol. Once it asks for it, the http server starts the transfer.
So, it is between the browser (as http client) and the http server.
Since http protocol does not takes into account the option to abort a transfer, the browser should implement a out-of-standard mechanism to programmatically abort the connection. But since this is not specified in any standard, i think you won't find any way to do that with javascript or any client side code.
Cancel with transparent base64 encoded GIF to avoid additional requests and double page load on android:
var img = new Image();
img.src = 'http://google.com/favicon.ico';
img.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEAAAAALAAAAAABAAEAAAI=;'
Although I can't find the bug report now, I believe this is a long-standing logged WebKit bug. Firefox (and IE I think) have more sane behavior. I'm going back a bit in my brain, but if I recall on those browsers, resetting the img.src will in fact cancel outstanding downloads. I am positive that Firefox does this when a download is "waiting in line" for a chance at an open HTTP connection, and I seem to recall that it will actually force close connections sometimes.
I've never found a way to coax WebKit based browsers into cancelling an img download in progress, whether it is just queued or already actively downloading.
This really sucks if you're making something like a mapping client and need more fine grained control over images.
Setting the .src property to an empty string should cancel the load:
//load image from url
var img = new Image();
img.src = 'http://somedomain.com/image.jpg';
......
//cancel load
img.src = '';
Yes, page is downloaded twice on Android when an img tag has an src="" attribute.
This still occurs on recent Android versions.
I have not found any other browser that does that.
But I found a solution: use an img tag without src attribute.
The ultimative answer is web workers.
Load the image inside an webworker and stopping the web worker will stop the image loading.
You can get the idea from this code:
https://github.com/NathanWalker/ng2-image-lazy-load
this work for me:
imageVarName.src = '';
imageVarName.onload = null;
imageVarName.onerror = null;
the src property must be a valid non-empty URL
So null or empty string are not legal (even though they sometimes work).
Use:
img.src='http://xxxx';
img.onerror=null;
(see here)
Sadly, setting src to an empty string does not work in WebKit-based browsers like Safari. Here is the link to the bug report which Stella mentioned.
https://bugs.webkit.org/show_bug.cgi?id=6656

JS Image Pre-loading blocked?

I am using a JQuery Plugin called lightbox (which is great btw). Problem is, I am accessing images on external sites and I think they are blocking lightbox from preloading them.
Specifically I have confirmed that picasa gives the preloader a 404 (using firebug), but if I right click the failed request in the firebug "net" tab, and "Open in new tab" The image loads fine.
This happens with any images from picasa, unless I've already viewed them (in which case I believe they are pulled from the brower's cache rather than loading them again)
There are a a few differences between the headers sent by the browser vs the preloader (also from firebug):
the preloader's "Accept" header is:
image/png,image/*;q=0.8,*/*;q=0.5
vs loading the image directly in the browser:
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
I suspect this is one way a remote server could differentiate a browser request from the javascript. What do you think?
Also, here is the preloader code from the plugin... just in case
// Image preload process
var objImagePreloader = new Image();
objImagePreloader.onload = function() {
$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
// Perfomance an effect in the image container resizing it
_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
// clear onLoad, IE behaves irratically with animated gifs otherwise
objImagePreloader.onload=function(){};
};
objImagePreloader.src = settings.imageArray[settings.activeImage][0];
update
apparently picasa is blocking me from displaying the full-size images at all whether part of the DOM or preloaded via javascript... not sure what to do about this
You could always add the preload IMG tags to the DOM in a hidden DIV instead of loading them with JavaScript. That way the browser is loading them "naturally".
solution
Picasa will let external sites load images up to 800px wide... if you try to use any larger than that on an external domain (not picasaweb.google.com) you will just get a 404
fortunately for me 800px is plenty... I was just trying to load the originals, which you're not allowed to do at all haha

Javascript: Cancel/Stop Image Requests

I have a website that makes heavy use of Ajax. Occasionally I need to load large image files on the page for the user. My question is, when these large image files are being download, is there a way to stop them if, say, the user navigates away from the page displaying the image? Thanks.
I had the exact same issue, when users 'paged' quickly through (ajax) search results the browser was still trying to download profile images for every page not just the current one. This code worked for me, called on the paging event just before the new search was run:
//cancel image downloads
if(window.stop !== undefined)
{
window.stop();
}
else if(document.execCommand !== undefined)
{
document.execCommand("Stop", false);
}
Essentially it's like clicking the "Stop" button on the browser.
Tested in IE, FireFox, Chrome, Opera and Safari
like this.
$(img).attr('src','');
Assuming that you are using ajax to load the images, you could simply abort the request in the window.onunload event. Declare a global variable for the XMLHttpRequest object that you are using.
var xhr;
//if using the XMLHttpRequest object directly
//you may already be doing something like this
function getImage(...){
xhr = new XMLHttpRequest();
xhr.open(....);
}
if using jQuery, you could assign the return value of the call you $.ajax() or $.get to xhr variable.
xhr = $.ajax(.....);
Handle the window.onunload and abort the request.
window.onunload = function(){
xhr.abort();
}
Reassigning the SRC tag to a different image does not work in IE7, it continues trying to download the first image.
Here is the setup:
I created an HTTP handler that is of type JPEG. It contains code that never finishes executing. So someImage.src=myhandler.ashx will perpetually sit there loading until it times out.
In the middle of this, press another button that reassigns the image to a small image file:
someImage.src=small.jpg
The request for myhandler.ashx does not end, even though we have reassigned the src.
Furthermore if you actually delete the node someImage.parentNode.removeChild(someImage) is still keeps trying to download myhandler.ashx
Tested with IE7 and monitored with HTTP Watch Pro.
The poor mans solution would be to simply set the SRC property of the image tag to an empty string, or point it towards a widget.
edit
Saw your comment, surprised it doesn't work with changing the SRC property to empty... try using a blank.gif or something.
If that doesn't work, you may be bounded by browser architecture, meaning you are S.O.L.

Categories

Resources