views:

404

answers:

5

I'd like to cancel a .load() operation, when the load() does not return in 5 seconds. If it's so I show an error message like 'sorry, no picture loaded'.

What I have is...

...the timeout handling:

jQuery.fn.idle = function(time, postFunction){  
    var i = $(this);  
    i.queue(function(){  
        setTimeout(function(){  
            i.dequeue();
            postFunction();  
        }, time);  
    });
    return $(this); 
};

... initializing of the error message timeout:

var hasImage = false;

$('#errorMessage')
    .idle(5000, function() {

        if(!hasImage) {
            // 1. cancel .load()            
            // 2. show error message
        }
    });

... the image loading:

$('#myImage')
     .attr('src', '/url/anypath/image.png')
     .load(function(){
         hasImage = true;
         // do something...
      });

The only thing I could not figure out is how to cancel the running load() (if it's possible).

Please help. Thanks!

Edit:

Another way: How do I prevent the .load() method to call it's callback function when it's returning?

A: 

I think the simplest thing to do would be to use $.ajax directly. That way you can start a timeout, and from the timeout set a flag that the handler on the ajax call can check. The timeout can also show a message or whatever.

Pointy
Hi Pointy, thanks for your answer. I had the same thought, but I don't want to break up these nice encapsulated handling of jQuery...
Dirk Jönsson
Well, the `.load()` API is synchronous, and that's that.
Pointy
hmm, may I have to change my question to: how do I prevent the .load() method to call it's callback function when it's returning...
Dirk Jönsson
I deleted the comment about `.load()` being synchronous - I don't think it actually is. Sorry about that. Nevertheless, I still don't know of any way to tell jQuery to abort the callback; the xhr object remains buried.
Pointy
A: 

I don't think you can get there from here - as @Pointy mentioned, you need to need to get to the XmlHttpRequest object so you can access the .abort() method on it. For that, you need the .ajax() jQuery API which returns the object to you.

Barring the ability to abort the request, another method to consider is to add knowledge of the timeout into the callback function. You could do this two ways - first:

var hasImage = false;

$('#errorMessage')
    .idle(5000, function() {

        if(!hasImage) {
            // 1. cancel .load()            
            // 2. show error message
            // 3. Add an aborted flag onto the element(s)
            $('#myImage').data("aborted", true);
        }
    });

And your callback:

$('#myImage')
     .attr('src', '/url/anypath/image.png')
     .load(function(){
         if($(this).data("aborted")){
             $(this).removeData("aborted");
             return;
         }
         hasImage = true;
         // do something...
      });

Or you could bypass the idle for this particular functionality:

$('#myImage')
     .attr('src', '/url/anypath/image.png')
     .data("start", (new Date()).getTime())
     .load(function(){
         var start = $(this).data("start");
         $(this).removeData("start");
         if(((new Date()).getTime() - start) > 5000)
             return;

         hasImage = true;
         // do something...
      });

Neither approach is ideal, but I don't think you can directly cancel load as of jQuery 1.4 - might be a nice feature request to the jQuery team, though.

Emil Lerch
+3  A: 

If you want any custom handling such as this, you simply can't use the jQuery.load() function. You'll have to upgrade to jQuery.ajax(), which I recommend anyway since you can do so much more with it, especially if you need any kind of error handling, it will be necessary.

Use the beforeSend option for jQuery.ajax and capture the xhr. Then you can create callback which can cancel the xhr after your timeout, and the callbacks as necessary.

This code is not tested, but should get you started.

var enableCallbacks = true;
var timeout = null;
jQuery.ajax({
  ....
  beforeSend(xhr) {
    timeout = setTimeout(function() {
      xhr.abort();
      enableCallbacks = false;
      // Handle the timeout
      ...
    }, 5000);
  },
  error: function(xhr, textStatus, errorThrown) {
    clearTimeout(timeout);
    if (!enableCallbacks) return;
    // Handle other (non-timeout) errors
  },
  success: function(data, textStatus) {
    clearTimeout(timeout);
    if (!enableCallbacks) return;
    // Handle the result
    ...
  }
});
fullware
fullware, thanks for your helpful answer! There is a small thing to correct: I had to replace the line "beforeSend(xhr) {" with "beforeSend: function(xhr) {"
Dirk Jönsson
+2  A: 

If you load this code after JQuery has been loaded you will be able to call .load() with a timeout parameter.

jQuery.fn.load = function( url, params, callback, timeout ) {
    if ( typeof url !== "string" ) {
        return _load.call( this, url );

    // Don't do a request if no elements are being requested
    } else if ( !this.length ) {
        return this;
    }

    var off = url.indexOf(" ");
    if ( off >= 0 ) {
        var selector = url.slice(off, url.length);
        url = url.slice(0, off);
    }

    // Default to a GET request
    var type = "GET";

    // If the second parameter was provided
    if ( params ) {
        // If it's a function
        if ( jQuery.isFunction( params ) ) {
            if( callback && typeof callback === "number"){
                timeout = callback;
                callback = params;
                params = null;
            }else{
                // We assume that it's the callback
                callback = params;
                params = null;
                timeout = 0;
            }
        // Otherwise, build a param string
        } else if( typeof params === "number"){
            timeout = params;
            callback = null;
            params = null;
        }else if ( typeof params === "object" ) {
            params = jQuery.param( params, jQuery.ajaxSettings.traditional );
            type = "POST";
            if( callback && typeof callback === "number"){
                timeout = callback;
                callback = null;
            }else if(! timeout){
                timeout = 0;
            }
        }
    }

    var self = this;

    // Request the remote document
    jQuery.ajax({
        url: url,
        type: type,
        dataType: "html",
        data: params,
        timeout: timeout,
        complete: function( res, status ) {
            // If successful, inject the HTML into all the matched elements
            if ( status === "success" || status === "notmodified" ) {
                // See if a selector was specified
                self.html( selector ?
                    // Create a dummy div to hold the results
                    jQuery("<div />")
                        // inject the contents of the document in, removing the scripts
                        // to avoid any 'Permission Denied' errors in IE
                        .append(res.responseText.replace(rscript, ""))

                        // Locate the specified elements
                        .find(selector) :

                    // If not, just inject the full result
                    res.responseText );
            }

            if ( callback ) {
                self.each( callback, [res.responseText, status, res] );
            }
        }
    });

    return this;
};

Not sure if you are interested in overwriting any "standard" JQuery functions, but this would allow you to use .load() the way you described.

Falle1234
A: 

$('#myImage').load(function(){...}) is not a function call to load the image, it is actually shorthand to bind a callback to the onload event.

Therefore, adding a timeout parameter to the .load() method as suggested in other answers will have no effect.

It think your two options are:

  1. Continue on the path you are following and do something like $('#myImage').attr('src', ''); to cancel the image load after it times out, or

  2. Find some way to use $.ajax( { ... , timeout: 5000, ...} ); to load the image instead of letting the browser do it automatically via the <img src="..."> attribute.

Tom