How to cancel an image from loading - javascript

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

Related

How to replay an animated GIF in javascript (vanilla) - Without JQuery

My current issue is that I have a loading bar animation on my web-based app that is shown (obviously) when the whole page or specific things are loading up. It is supposed to look like one of those Samsung TV Apps so it needs to be quite polished with the UX.
What me and my team are doing right now is a mix between creating an element for it and I assumed it gets cached in the local device which is an issue. I've known of a few ways that I can go around this like adding a Math.random() query at the end of the src url but I'd rather not follow that route for now.
I also saw a way that I believe involved simply setting the element.src = 'theSameUrl.gif' URL to be the same and I assume forcing the device to reload the file instead of using the cached one.
I would also be open to trying new file types that could make this a lot easier but I must keep in mind that this app will work on a LOT of different hardware, from Samsung TV's to BT Boxes or even Virgin Media Tv Boxes, amazon firestick etc.
At this point I'll take anything :P
You can "force it" to reload by wiping it source: img.src = ""
Then you set it again: img.src = "your_src_path"
This way your .gif will start from zero, at least on Edge, Chrome and Firefox, it should work the same way on a TV.

How to use javascript to preload images

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

Dynamically created iframe used to download file triggers onload with firebug but not without

EDIT: as this problem is now "solved" to the point of working, I am looking to have the information on why. For the fix, see my comment below.
I have an web application which repeatedly downloads wav files dynamically (after a timeout or as instructed by the user) into an iframe in order to trigger the a default audio player to play them. The application targets only FF 2 or 3. In order to determine when the file is downloaded completely, I am hoping to use the window.onload handler for the iframe. Based on this stackoverflow.com answer I am creating a new iframe each time. As long as firebug is enabled on the browser using the application, everything works great. Without firebug, the onload never fires. The version of firebug is 1.3.1, while I've tested Firefox 2.0.0.19 and 3.0.7. Any ideas how I can get the onload from the iframe to reliably trigger when the wav file has downloaded? Or is there another way to signal the completion of the download? Here's the pertinent code:
HTML (hidden's only attribute is display:none;):
<div id="audioContainer" class="hidden">
</div>
JavaScript (could also use jQuery, but innerHTML is faster than html() from what I've read):
waitingForFile = true; // (declared at the beginning of closure)
$("#loading").removeClass("hidden");
var content = "<iframe id='audioPlayer' name='audioPlayer' src='" +
/path/to/file.wav + "' onload='notifyLoaded()'></iframe>";
document.getElementById("audioContainer").innerHTML = content;
And the content of notifyLoaded:
function notifyLoaded() {
waitingForFile = false; // (declared at beginning of the closure)
$("#loading").addClass("hidden");
}
I have also tried creating the iframe via document.createElement, but I found the same behavior. The onload triggered each time with firebug enabled and never without it.
EDIT:
Fixed the information on how the iframe is being declared and added the callback function code. No, no console.log calls here.
Old question but for future reference:
As far as my experience onLoad is not called for file downloads. A way to solve it is to use cookies like they do here http://gruffcode.com/2010/10/28/detecting-the-file-download-dialog-in-the-browser/
Here's an example that works for me, without Firebug open (tested in FF 3.6.2 Mac): http://www.jsfiddle.net/Kukry/
I'm using the jQuery .load() event instead of onload.
var iframe = $("<iframe/>").load(function () {
alert("loaded");
}).attr({
src: "http://code.jquery.com/jquery-1.4.2.min.js"
}).appendTo($("#thediv"));
Note that I'm loading a JavaScript file, not an audio file, so that might make a difference.
Maybe you call some Firebug internal function, like console.log(), somewhere? In that case, Firefox will threw an exception which can stop the execution if Firebug is not active.

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