Check image HTTP status codes using jQuery/JS? - javascript

is it possible to check the status codes of images using jQuery/JS?
For example,
img1 = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/260px-YellowLabradorLooking_new.jpg";
if(statusCheck(img1) == 404){
/do something
}elseif(statusCheck(img1) == 403){
//do something else
}elseif(statusCheck(img1) == 304){
//do something else
}
Thanks

You can construct an Image object, which isn't affected by cross-origin restrictions:
var image = new Image();
image.src = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/260px-YellowLabradorLooking_new.jpg"
image.onload = function() {
alert('Image has loaded');
};
image.onerror = function() {
alert('Image did not load');
};
Image loading is asynchronous, so making a function that returns the error code won't be a good idea.
Demo: http://jsfiddle.net/Blender/apyL7/
Also, there doesn't seem to be a way to get the response code, so you're limited to knowing only whether the image loaded or not.

Related

First Image not being loaded

I have the following code snippet which is called on the success of the image uploading procedure.
success(data){
$avatar.attr('src', "/images/common/loading.gif");
$avatar.attr('src', data.url);
}
Here $avatar is the container for an image tag. The idea is to load this image with loading.gif until data.url is loaded successfully. Here data.url may contain a large size image which takes long time to load.
The problem is loading.gif is never loaded to the image container until I use setTimeOut as:
success(data){
$avatar.attr('src', "/images/common/loading.gif");
setTimeOut(function(){
$avatar.attr('src', data.url);
},100);
}
Can anyone suggest me some different approach rather than to use setTimeOut?
Showing uploaded image is more important than showing loader image But if you are doing it your way, go with the onload-event.
Also listen onerror event if loader image fails, or else avatar image will never get loaded!
success(data) {
var loader = new Image();
var loadMainImage = function() {
var mainImage = new Image();
mainImage.onload = function() { //avatar is loaded!
$avatar.attr('src', this.src);
}
mainImage.src = data.url;
}
loader.onload = function() { //loader is loaded!
$avatar.attr('src', this.src);
loadMainImage();
};
loader.onerror = mainImage; //loader is failed!
loader.src = "/images/common/loading.gif";
}
I think you can use beforeSend to handle async promises

JavaScript create images and document.readyState

To make sure a document is ready before doing stuff, i do the following :
(function() {
var interval = window.setInterval(function() {
if("complete" === document.readyState) {
window.clearInterval(interval);
// Some stuff
}
}, 10);
})();
If somewhere in my code i create an image from JavaScript like this :
var image = new Image();
image.onload = function() {
// Some other stuff
};
image.src = 'some_url';
Will the check I perform on document.readyState also wait for "image" to be loaded, or will it just wait for the images present in the HTML code, and only those, to be loaded ?
Thanks in advance.
You don't need your setInterval.
From the MDN :
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images and sub-frames have finished loading.
You can simply do this for the statically included images :
window.onload = function() {
// Some stuff
};
As this doesn't take into account the images you create later, you may do this :
window.onload = function() {
var image = new Image();
image.onload = function(){
// Some stuff
};
image.src = 'some_url';
};
In jquery document.ready() function is call when entire html page is ready or we can say bind (in technical terms).
You should try with increasing Interval time. or include image load callback for performing the stuff.

image.onload event and browser cache

I want to create an alert box after an image is loaded, but if the image is saved in the browser cache, the .onload event will not be fired.
How do I trigger an alert when an image has been loaded regardless of whether the image has been cached or not?
var img = new Image();
img.src = "img.jpg";
img.onload = function () {
alert("image is loaded");
}
As you're generating the image dynamically, set the onload property before the src.
var img = new Image();
img.onload = function () {
alert("image is loaded");
}
img.src = "img.jpg";
Fiddle - tested on latest Firefox and Chrome releases.
You can also use the answer in this post, which I adapted for a single dynamically generated image:
var img = new Image();
// 'load' event
$(img).on('load', function() {
alert("image is loaded");
});
img.src = "img.jpg";
Fiddle
If the src is already set then the event is firing in the cached case before you even get the event handler bound. So, you should trigger the event based off .complete also.
code sample:
$("img").one("load", function() {
//do stuff
}).each(function() {
if(this.complete || /*for IE 10-*/ $(this).height() > 0)
$(this).load();
});
There are two possible solutions for these kind of situations:
Use the solution suggested on this post
Add a unique suffix to the image src to force browser downloading it again, like this:
var img = new Image();
img.src = "img.jpg?_="+(new Date().getTime());
img.onload = function () {
alert("image is loaded");
}
In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again
I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {}) instead of document.ready would solve part of issue (if you are not ajaxing the page).
I found that you can just do this in Chrome:
$('.onload-fadein').each(function (k, v) {
v.onload = function () {
$(this).animate({opacity: 1}, 2000);
};
v.src = v.src;
});
Setting the .src to itself will trigger the onload event.

How to check if picture is loaded?

How can I check if a picture is already loaded?
image.src = ay.url_static + 'uploads/apps/' + thumbnail.uid + '.png';
image.onload = function(e)
{
// [..]
};
I know how to trigger a callback upon image is loaded, but how do I check if picture is loaded at the moment?
I'm not sure what you want, but from what I understand you need to know if an image is loaded at any moment in time, right?
I've one function do check if the image is valid. You can use it to see if the image is already loaded also if you want. If you don't want to know if the image is valid, you can use only the img.complete property.
function IsImageLoaded(img) {
if (!img.complete) {
return false;
}
if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
return false;
}
return true;
}
Set image.loaded = false, and then set image.loaded = true in your onload callback and check that property later?
Or image.complete seems like a legit property, if not W3C.
assuming you're using jQuery...
image.onload = function(e)
{
$(this).data({loaded: true});
};
later...
if($(yourImage).data('loaded')) {
// it's loaded!
} else {
// it's not
}
jQuery's .data() is great for setting variables specific to elements.

how to detect if a URL points to a SWF

Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG?
The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension.
so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different.
Thanks!
You could use javascript to detect if it is a image by creating a dynamic img-tag.
function isImage(url, callback) {
var img = document.createElement('img');
img.onload = function() {
callback(url);
}
img.src = url;
}
And then calling it with:
isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); });
Update
This version will always execute the callback with a boolean value.
function isImage(url) {
var img = document.createElement('img');
img.onload = function() {
isImageCallback(url, true);
}
img.onerror = function() {
isImageCallback(url, false);
}
img.src = url;
}
function isImageCallback(url, result) {
if (result)
alert(url + ' is an image');
else
alert(url + ' is not an image');
}
Put your logic in the isImageCallback function.
I would extend Sijin's answer by saying:
An HTTP HEAD request to the url can be used to examine the resource's mime-type. You
won't need to download the rest of the file that way.
Completely untested, basicly just an idea:
function isImage(url)
{
var http = getHTTPObject();
http.onreadystatechange = function ()
{
if (http.readyState == 4)
{
var contentType = http.getResponseHeader("Content Type");
if (contentType == "image/gif" || contentType == "image/jpeg")
return true;
else
return false;
}
}
http.open("HEAD",url,true);
http.send(null);
}
function getHTTPObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
return false;
}
I am not sure the of the exact setup you have, but can you use the HTTP response and check the mime-type to determine image vs flash?
If the URL doesn't have an extension then there is no way to tell without requesting the file from the server.

Categories

Resources