Reputation: 21
I have got a JSP page which loads images dynamically. Now, I also have some "input" elements on this page such as a checkbox and select menus which are being created using a javascript module (creating a different styling for the input elements).
My issue is, one of the images the page is trying to load does not exist on the external link it is trying to open. The server only responds after 15 seconds to say that the image does not exist. This means that I have to wait 15 seconds for my "input" elements to load, since the activation of the javascript module only happens after all images are fully loaded on my page.
Is there a way for me to set a timeout for loading images, such that for example, after 5 seconds of trying to load an image, it stops the request?
Thanks,
Michael
Upvotes: 2
Views: 2974
Reputation: 16569
You could simply set a timeout before loading the image as well as testing for a load error.
function LoadImage(yourImage) {
var imageTimer = setTimeout(function () {
//image could not be loaded:
alert('image load timed out');
}, 10000); //10 seconds
$(yourImage).load(function (response, status, xhr) {
if (status == 'error') {
//image could not be loaded:
alert('failed to load image');
} else {
//image was loaded:
clearTimeout(imageTimer);
//display your image...
}
});
}
Upvotes: 0
Reputation:
Thank you very much for all your answers, you have given me great clues as to what I should have actually done.
In the JavaScript module that creates the "input" elements, the following line was written at the bottom of the script:
window.onload = Custom.init;
I basically took this line out, and wrote it instead in my header.jsp file which is included in all of my pages, in the following way:
$(document).ready(function() {
Custom.init();
});
Thanks again for your quick replies,
Michael
Upvotes: 0
Reputation: 108500
You should use a DOMready event or trigger the module before closing the body tag if you want your scripts to execute before images are loaded/not loaded.
Regarding checking if image exists, you can do something like:
var img = $(new Image()).load(function() {
// image exists
}).error(function() {
// image does not exist
}).attr('src','some-image-url.jpg');
This should work cross-browser (it uses the onError event: https://developer.mozilla.org/En/XUL/Image#a-onerror)
Upvotes: 2
Reputation: 449525
I think this can't be done as the process of loading images is very deeply entrenched in the browser and can't be accessed or terminated directly.
A possible workaround:
Check after 5 seconds whether the image has proper dimensions yet. If it doesn't, remove the image's DOM element. I'm not sure this will stop loading but I think it should.
Upvotes: 0