Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 873
frio80 Avatar asked May 30 '09 18:05

frio80


3 Answers

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 image 187
SavoryBytes Avatar answered Oct 20 '22 23:10

SavoryBytes


like this.

$(img).attr('src','');
like image 38
bbokkun Avatar answered Oct 20 '22 23:10

bbokkun


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();
}
like image 32
ichiban Avatar answered Oct 20 '22 23:10

ichiban