Post-loading : check if an image is in the browser cache - javascript

Short version question :
Is there navigator.mozIsLocallyAvailable equivalent function that works on all browsers, or an alternative?
Long version :)
Hi,
Here is my situation :
I want to implement an HtmlHelper extension for asp.net MVC that handle image post-loading easily (using jQuery).
So i render the page with empty image sources with the source specified in the "alt" attribute.
I insert image sources after the "window.onload" event, and it works great.
I did something like this :
$(window).bind('load', function() {
var plImages = $(".postLoad");
plImages.each(function() {
$(this).attr("src", $(this).attr("alt"));
});
});
The problem is : After the first loading, post-loaded images are cached. But if the page takes 10 seconds to load, the cached post-loaded images will be displayed after this 10 seconds.
So i think to specify image sources on the "document.ready" event if the image is cached to display them immediatly.
I found this function : navigator.mozIsLocallyAvailable to check if an image is in the cache. Here is what I've done with jquery :
//specify cached image sources on dom ready
$(document).ready(function() {
var plImages = $(".postLoad");
plImages.each(function() {
var source = $(this).attr("alt")
var disponible = navigator.mozIsLocallyAvailable(source, true);
if (disponible)
$(this).attr("src", source);
});
});
//specify uncached image sources after page loading
$(window).bind('load', function() {
var plImages = $(".postLoad");
plImages.each(function() {
if ($(this).attr("src") == "")
$(this).attr("src", $(this).attr("alt"));
});
});
It works on Mozilla's DOM but it doesn't works on any other one. I tried navigator.isLocallyAvailable : same result.
Is there any alternative?

after some reseach, I found a solution :
The idea is to log the cached images, binding a log function on the images 'load' event.
I first thought to store sources in a cookie, but it's not reliable if the cache is cleared without the cookie. Moreover, it adds one more cookie to HTTP requests...
Then i met the magic : window.localStorage (details)
The localStorage attribute provides
persistent storage areas for domains
Exactly what i wanted :). This attribute is standardized in HTML5, and it's already works on nearly all recent browsers (FF, Opera, Safari, IE8, Chrome).
Here is the code (without handling window.localStorage non-compatible browsers):
var storage = window.localStorage;
if (!storage.cachedElements) {
storage.cachedElements = "";
}
function logCache(source) {
if (storage.cachedElements.indexOf(source, 0) < 0) {
if (storage.cachedElements != "")
storage.cachedElements += ";";
storage.cachedElements += source;
}
}
function cached(source) {
return (storage.cachedElements.indexOf(source, 0) >= 0);
}
var plImages;
//On DOM Ready
$(document).ready(function() {
plImages = $(".postLoad");
//log cached images
plImages.bind('load', function() {
logCache($(this).attr("src"));
});
//display cached images
plImages.each(function() {
var source = $(this).attr("alt")
if (cached(source))
$(this).attr("src", source);
});
});
//After page loading
$(window).bind('load', function() {
//display uncached images
plImages.each(function() {
if ($(this).attr("src") == "")
$(this).attr("src", $(this).attr("alt"));
});
});

The most efficient, simple, and widely supported way to check if an image has already been cached is to do the following...
Create an image object
Set the src property to the desired url
Check the completed attribute immediately to see if the image is already cached
Set the src attribute back to "" (empty string), so that the image is not unnecessarily loaded (unless of coarse you want to load it at this time)
Like so...
function isCached(src) {
const img = new Image();
img.src = src;
const complete = img.complete;
img.src = "";
return complete;
}
In your case, it could be implemented like so...
const lazyImages = document.querySelectorAll(".postLoad");
for (const img of lazyImages) {
if ((!img.src || !isCached(img.src)) && img.getAttribute("alt")) {
img.src = img.getAttribute("alt");
}
}
That being said, I'd advise against using the alt attribute for this purpose, you should use something like data-src instead.

An ajax request for the image would return almost immediately if it is cached. Then use setTimeout to determine if its not ready and cancel the request so you can requeue it for later.
Update:
var lqueue = [];
$(function() {
var t,ac=0;
(t = $("img")).each(
function(i,e)
{
var rq = $.ajax(
{
cache: true,
type: "GET",
async:true,
url:e.alt,
success: function() { var rq3=rq; if (rq3.readyState==4) { e.src=e.alt; } },
error: function() { e.src=e.alt; }
});
setTimeout(function()
{
var k=i,e2=e,r2=rq;
if (r2.readyState != 4)
{
r2.abort();
lqueue.push(e2);
}
if (t.length==(++ac)) loadRequeue();
}, 0);
}
);
});
function loadRequeue()
{
for(var j = 0; j < lqueue.length; j++) lqueue[j].src=lqueue[j].alt;
}

I have a remark about your empty image sources. You wrote:
So i render the page with empty image sources with the source specified in the "alt" attribute. I insert image sources after the "window.onload" event, and it works great.
I've ran into problems with this in the past, because in some browsers empty src attributes cause extra requests. Here's what they do (copied from Yahoo! performance rules, there's also a blog post on that issue with more detail):
Internet Explorer makes a request to the directory in which the page is located.
Safari and Chrome make a request to the actual page itself.
Firefox 3 and earlier versions behave the same as Safari and Chrome, but version 3.5 addressed this issue[bug 444931] and no longer sends a request.
Opera does not do anything when an empty image src is encountered.
We also use a lot of jQuery on our site, and it has not always been possible to avoid empty image tags. I've chosen to use a 1x1 px transparent gif like so: src="t.gif" for images that I only insert after pageload. It is very small and gets cached by the browser. This has worked very well for us.
Cheers, Oliver

Just in case others may come across the same issue. some of the solutions provided here (namely storing the cache info in a local browser data storage) could break for two reasons. Firstly if cache of the image expires and secondly if the cache is cleared by the user. Another approach would be to set the source of image to an placeholder. Then changing the source to the image path/name. This way it becomes the responsibility of the browser to check its own cache. Should work with most browsers regardless of their API.

In 2017, Resource Timing API can help you check this using PerformanceResourceTiming.transferSize property. This property shall return non-zero transfer size when it is downloaded from server (not cached) and returns zero if fetched from a local cache.
Reference : https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/transferSize

For anyone who might be trying to solve this problem with React I used the complete image property to solve it in React this way:
import React, { useState, useEffect, useRef } from 'react'
const Component= () => {
const [isLoadedImage, setLoadedImage] = useState(false)
const imageRef = useRef(null)
useEffect(() => {
const imgEl = imageRef.current
if (imgEl && imgEl.complete && !isLoadedImage) setLoadedImage(true)
})
return (
<img
onLoad={() => (!isLoadedImage ? setLoadedImage(true) : null)}
ref={imageRef}
/>
)
}

Related

How can I load multiple versions of the same video on a page after page load via javascript without downloading multiple versions of the video file?

I'm trying to load multiple versions of the same video on a page. The script runs after page load, but I have to loop through the sources to check if they have been added to the DOM already (otherwise they download the same file multiple times). If that source already exists, the other duplicates of the video must wait until the first version is downloaded, via an eventListener, before loading the duplicate source and using that cached version of the first video to populate the duplicates (so that they don't download multiple times).
It seems to work fine when I test it in the Chrome network tab, the sources are only downloaded once, but when I look at the Lighthouse diagnostics it is telling me that the js execution time needs to be reduced. Is this because of the looping?
I also keep running into the issue of PageSpeed Insights giving me the message: "Oops! Something went wrong. PageSpeed Insights encountered a problem collecting the lab data."
What am I doing wrong here?
var i = 1,
sourceID,
arraySRC = [];
document.querySelectorAll("video source").forEach(function(source, sourceIndex) {
if (source.hasAttribute("data-small-src") && source.getAttribute("data-small-src") != "") {
source.id = "vidsource-" + i;
sourceID = "vidsource-" + i;
var src = source.getAttribute("data-small-src"),
sourceLoading = false,
firstMatchID;
// loop through array to see if source value already exists
arraySRC.forEach(function(itemSRC, arrayIndex) {
// if source value already exists in array
if (itemSRC.split(",")[1] == src) {
sourceLoading = true;
firstMatchID = itemSRC.split(",")[0]
return
}
});
if (sourceLoading == false) {
const node = document.createElement("source");
source.parentElement.appendChild(node);
node.setAttribute("src", src);
} else {
document.querySelector("#" + firstMatchID).addEventListener('loadeddata', function() {
const node = document.createElement("source");
source.parentElement.appendChild(node);
node.setAttribute("src", src);
}, false);
}
// add source to array
arraySRC.push(sourceID + "," + src);
i = i + 1;
}
});
(I have left out the load event for the script since I am using a Barba.js hook)

How to detect if any of css/js files failed to load and alert user to refresh browser [duplicate]

I have an HTML page where several JavaScript, CSS and images files are referenced. These references are dynamically injected and user can manually copy the HTML page and the support files to another machine.
If some JS or CSS are missing, the browser complains in the console. For example:
Error GET file:///E:/SSC_Temp/html_005/temp/Support/jquery.js
I need somehow these errors reported back to me on the inline JavaScript of the HTML page so I can ask user to first verify that support files are copied correctly.
There's the window.onerror event which just inform me that there's a JS error on the page such as an Unexpected Syntax error, but this doesn't fire in the event of a 404 Not Found error. I want to check for this condition in case of any resource type, including CSS, JS, and images.
I do not like to use jQuery AJAX to verify that file physically exists - the I/O overhead is expensive for every page load.
The error report has to contain the name of the file missing so I can check if the file is core or optional.
Any Ideas?
To capture all error events on the page, you can use addEventListener with the useCapture argument set to true. The reason window.onerror will not do this is because it uses the bubble event phase, and the error events you want to capture do not bubble.
If you add the following script to your HTML before you load any external content, you should be able to capture all the error events, even when loading offline.
<script type="text/javascript">
window.addEventListener('error', function(e) {
console.log(e);
}, true);
</script>
You can access the element that caused the error through e.target. For example, if you want to know what file did not load on an img tag, you can use e.target.src to get the URL that failed to load.
NOTE: This technically will not detect the error code, it detects if the image failed to load, as it technically behaves the same regardless of the status code. Depending on your setup this would probably be enough, but for example if a 404 is returned with a valid image it will not trigger an error event.
you can use the onload and onerror attributes to detect the error
for example upon loading the following html it gives alert error1 and error2 you can call your own function e.g onerror(logError(this);) and record them in an Array and once the page is fully loaded post is with single Ajax call.
<html>
<head>
<script src="file:///SSC_Temp/html_005/temp/Support/jquery.js" onerror="alert('error1');" onload="alert('load');" type="text/javascript" ></script>
</head>
<body>
<script src="file:///SSC_Temp/html_005/temp/Support/jquery.js" onerror="alert('error2');" onload="alert('load');" type="text/javascript" ></script>
</body>
</html>
I've put together the code below in pure JavaScript, tested, and it works.
All the source code (html, css, and Javascript) + images and example font is here: on github.
The first code block is an object with methods for specific file extensions: html and css.
The second is explained below, but here is a short description.
It does the following:
the function check_file takes 2 arguments: a string path and a callback function.
gets the contents of given path
gets the file extension (ext) of the given path
calls the srcFrom [ext] object method that returns an array of relative paths that was referenced in the string context by src, href, etc.
makes a synchronous call to each of these paths in the paths array
halts on error, and returns the HTTP error message and the path that had a problem, so you can use it for other issues as well, like 403 (forbidden), etc.
For convenience, it resolves to relative path names and does not care about which protocol is used (http or https, either is fine).
It also cleans up the DOM after parsing the CSS.
var srcFrom = // object
{
html:function(str)
{
var prs = new DOMParser();
var obj = prs.parseFromString(str, 'text/html');
var rsl = [], nds;
['data', 'href', 'src'].forEach(function(atr)
{
nds = [].slice.call(obj.querySelectorAll('['+atr+']'));
nds.forEach(function(nde)
{ rsl[rsl.length] = nde.getAttribute(atr); });
});
return rsl;
},
css:function(str)
{
var css = document.createElement('style');
var rsl = [], nds, tmp;
css.id = 'cssTest';
css.innerHTML = str;
document.head.appendChild(css);
css = [].slice.call(document.styleSheets);
for (var idx in css)
{
if (css[idx].ownerNode.id == 'cssTest')
{
[].slice.call(css[idx].cssRules).forEach(function(ssn)
{
['src', 'backgroundImage'].forEach(function(pty)
{
if (ssn.style[pty].length > 0)
{
tmp = ssn.style[pty].slice(4, -1);
tmp = tmp.split(window.location.pathname).join('');
tmp = tmp.split(window.location.origin).join('');
tmp = ((tmp[0] == '/') ? tmp.substr(1) : tmp);
rsl[rsl.length] = tmp;
}
});
});
break;
}
}
css = document.getElementById('cssTest');
css.parentNode.removeChild(css);
return rsl;
}
};
And here is the function that gets the file contents and calls the above object method according to the file extension:
function check_file(url, cbf)
{
var xhr = new XMLHttpRequest();
var uri = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function()
{
var ext = url.split('.').pop();
var lst = srcFrom[ext](this.response);
var rsl = [null, null], nds;
var Break = {};
try
{
lst.forEach(function(tgt)
{
uri.open('GET', tgt, false);
uri.send(null);
if (uri.statusText != 'OK')
{
rsl = [uri.statusText, tgt];
throw Break;
}
});
}
catch(e){}
cbf(rsl[0], rsl[1]);
};
xhr.send(null);
}
To use it, simply call it like this:
var uri = 'htm/stuff.html'; // html example
check_file(uri, function(err, pth)
{
if (err)
{ document.write('Aw Snap! "'+pth+'" is missing !'); }
});
Please feel free to comment and edit as you wish, i did this is a hurry, so it may not be so pretty :)
#alexander-omara gave the solution.
You can even add it in many files but the window handler can/should be added once.
I use the singleton pattern to achieve this:
some_global_object = {
error: (function(){
var activate = false;
return function(enable){
if(!activate){
activate = true;
window.addEventListener('error', function(e){
// maybe extra code here...
// if(e.target.custom_property)
// ...
}, true);
}
return activate;
};
}());
Now, from any context call it as many times you want as the handler is attached only once:
some_global_object.error();

Hide Image When Anchor HREF Source Is Not Present

I would like to poll an anchor's href source about once every 5 seconds, to see whether a file at that address is present. When it is present, display an image in the anchor. In other words, the link is basically not there unless the file is present.
I'm guessing I would have to poll using an http HEAD request to determine whether the file exists, then toggle the image appropriately. Once the file has been determined to exist, I can stop polling and leave the image visible.
Is there a better way to do this, and can anyone suggest some script that would handle this functionality?
If your server is configured to do so you can use:
http://api.jquery.com/jQuery.ajax/
To poll for the file's existence by using the statusCode map
function checkFile() {
$.ajax({
statusCode: {
404: function() {
//file does not yet exist
setTimeout(checkFile, 5000);
}
200: function() {
//file exists.
showImage();
}
}
});
}
You may want to capture a few more edge cases though, (for example, an error callback).
// note, this piece of code assumes to be using jQuery
var interval = setInterval(function(){
var _el=$('#hrefId');
var href = _el.attr('href');
if(href == null || typeof href == 'undefined' || href == '')
return;
ajax call to href(in case on ur server(!) )
// on success
_el.attr('href','TheLink');
$('img', _el).show(); // show image
}, 5);
You can also use a socket library so the server can push a notification when the image is ready. socket.io seems like a good options here.
Another way would be to listen for the error event on the image, then wait for x milliseconds before trying to load it again. This is quite easy to implement, because every time you define a src attribute, the browser will add new listeners.
It’s basically the same as your meta-description but you don’t need to use ajax. You will also be able to load images from other domains (ajax have a cross-site policy):
var img = new Image(),
src = '/path/to/image.jpg';
img.onload = function() {
console.log('loaded', img);
};
img.onerror = function() {
window.setTimeout(function() {
img.src = src;
},500);
};
img.src = src;​
Here is a proof of concept: http://jsfiddle.net/L2L3U/. The program will try to load a 404 image for three seconds, after that I change the src to a real image and it will display it.

Asynchronously load images with jQuery

I want to load external images on my page asynchronously using jQuery and I have tried the following:
$.ajax({
url: "http://somedomain.com/image.jpg",
timeout:5000,
success: function() {
},
error: function(r,x) {
}
});
But it always returns error, is it even possible to load image like this?
I tried to use .load method and it works but I have no idea how I can set timeout if the image is not available (404). How can I do this?
No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:
var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#something").append(img);
}
});
IF YOU REALLY NEED TO USE AJAX...
I came accross usecases where the onload handlers were not the right choice. In my case when printing via javascript. So there are actually two options to use AJAX style for this:
Solution 1
Use Base64 image data and a REST image service. If you have your own webservice, you can add a JSP/PHP REST script that offers images in Base64 encoding. Now how is that useful? I came across a cool new syntax for image encoding:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE..."/>
So you can load the Image Base64 data using Ajax and then on completion you build the Base64 data string to the image! Great fun :). I recommend to use this site http://www.freeformatter.com/base64-encoder.html for image encoding.
$.ajax({
url : 'BASE64_IMAGE_REST_URL',
processData : false,
}).always(function(b64data){
$("#IMAGE_ID").attr("src", "data:image/png;base64,"+b64data);
});
Solution2:
Trick the browser to use its cache. This gives you a nice fadeIn() when the resource is in the browsers cache:
var url = 'IMAGE_URL';
$.ajax({
url : url,
cache: true,
processData : false,
}).always(function(){
$("#IMAGE_ID").attr("src", url).fadeIn();
});
However, both methods have its drawbacks: The first one only works on modern browsers. The second one has performance glitches and relies on assumption how the cache will be used.
cheers,
will
Using jQuery you may simply change the "src" attribute to "data-src". The image won't be loaded. But the location is stored with the tag. Which I like.
<img class="loadlater" data-src="path/to/image.ext"/>
A Simple piece of jQuery copies data-src to src, which will start loading the image when you need it. In my case when the page has finished loading.
$(document).ready(function(){
$(".loadlater").each(function(index, element){
$(element).attr("src", $(element).attr("data-src"));
});
});
I bet the jQuery code could be abbreviated, but it is understandable this way.
$(<img />).attr('src','http://somedomain.com/image.jpg');
Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.
You can use a Deferred objects for ASYNC loading.
function load_img_async(source) {
return $.Deferred (function (task) {
var image = new Image();
image.onload = function () {task.resolve(image);}
image.onerror = function () {task.reject();}
image.src=source;
}).promise();
}
$.when(load_img_async(IMAGE_URL)).done(function (image) {
$(#id).empty().append(image);
});
Please pay attention: image.onload must be before image.src to prevent problems with cache.
If you just want to set the source of the image you can use this.
$("img").attr('src','http://somedomain.com/image.jpg');
This works too ..
var image = new Image();
image.src = 'image url';
image.onload = function(e){
// functionalities on load
}
$("#img-container").append(image);
AFAIK you would have to do a .load() function here as apposed to the .ajax(), but you could use jQuery setTimeout to keep it live (ish)
<script>
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
$("#placeholder").load("PATH TO IMAGE");
var refreshId = setInterval(function() {
$("#placeholder").load("PATH TO IMAGE");
}, 500);
});
</script>
use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:
$("#img_id").error(function(){
//$(this).hide();
//alert("img not loaded");
//some action you whant here
});
careful - .error() event will not trigger when the src attribute is empty for an image.
//Puedes optar por esta solución:
var img = document.createElement('img');
img.setAttribute('src', element.source)
img.addEventListener('load', function(){
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#imagenesHub").append(img);
}
});
$(function () {
if ($('#hdnFromGLMS')[0].value == 'MB9262') {
$('.clr').append('<img src="~/Images/CDAB_london.jpg">');
}
else
{
$('.clr').css("display", "none");
$('#imgIreland').css("display", "block");
$('.clrIrland').append('<img src="~/Images/Ireland-v1.jpg">');
}
});

Dynamically Preloading/Displaying Webcam Snapshots on a Web Page Using AJAX

I have an IP Camera that streams out live video to a web site of mine. Problem is, it is powered by an ActiveX control. Even worse, this control is unsigned. To provide a more secure alternative to the people that are using browsers other than IE, or are (rightfully) unwilling to change their security settings, I am tapping into the cameras built in snap-shot script that serves up a 640x480 live JPEG image. The plan was to update the image live on the screen every ~500ms using Javascript without having to reload the entire page.
I tried using the Image() object to pre-load the image and update the SRC attribute of the image element when onload fired:
function updateCam() {
var url = "../snapshot.cgi?t=" + new Date().getTime();
img = new Image();
img.onload = function() {
$("#livePhoto").attr("src", url);
camTimer = setTimeout(updateCam, 500);
}
img.src = url;
}
This worked decently, but it was difficult to determine when the camera had been disabled, which I needed to do in order to degrade gracefully. The internal snapshot script is setup to return an HTTP status code of 204 (No Content) under this circumstance, and of course there is no way for me to detect that using the Image object. Additionally, the onload event was not 100% reliable.
Therefore, I am using the jQuery (version 1.2.6) ajax function to do a GET request on the URL, and on the complete callback I evaluate the status code and set the URL accordingly:
function updateCam() {
var url = "../snapshot.cgi?t=" + new Date().getTime();
$.ajax({
type: "GET",
url: url,
timeout: 2000,
complete: function(xhr) {
try {
var src = (xhr.status == 200) ? url : '../i/cam-oos.jpg';
$("#livePhoto").attr("src", src);
}
catch(e) {
JoshError.log(e);
}
camTimer = setTimeout(updateCam, 500);
}
});
}
And this works beautifully. But only in IE! This is the question that I would like to have answered: Why doesn't this work in Firefox or Chrome? The complete event does not even fire in Firefox. It does fire in Chrome, but only very rarely does setting the SRC actually load the image that was requested (usually it displays nothing).
Posting a second answer, because the first was just really incorrect. I can't test this solution (because I don't have access to your webcam script), but I would suggest trying to sanitise the response from the camera - since you obviously can't handle the raw image data, try adding the dataFilter setting like so:
function updateCam() {
var url = "../snapshopt.cgi?t=" + new Date().getTime();
$.ajax({
type: "GET",
url: url,
timeout: 2000,
dataFilter : function(data, type) {
return '<div></div>' //so it returns something...
},
complete: function(xhr) {
try {
var src = (xhr.status == 200) ? url : '../i/cam-oos.jpg';
$("#live").attr("src", src);
}
catch(e) {
JoshError.log(e);
}
camTimer = setTimeout(updateCam, 500);
}
});
}
Like I said, I haven't been able to test this - but it might allow jquery to use the status codes without breaking like crazy.
img.onerror = function(){
alert('offline');
}
Well, I ended up using the data URI scheme (hat tip to Eric Pascarello) for non-IE browsers. I wrote a HTTP handler (in VB.NET) to proxy the IP camera and base-64 encode the image:
Imports Common
Imports System.IO
Imports System.Net
Public Class LiveCam
Implements IHttpHandler
Private ReadOnly URL As String = "http://12.34.56.78/snapshot.cgi"
Private ReadOnly FAIL As String = Common.MapPath("~/i/cam-oos.jpg")
Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
Dim Data As Byte()
With context.Response
.ContentEncoding = Encoding.UTF8
.ContentType = "text/plain"
.Write("data:image/png;base64,")
Try
Using Client As New WebClient()
Data = Client.DownloadData(URL)
End Using
Catch ex As WebException
Data = File.ReadAllBytes(FAIL)
End Try
.Write(Convert.ToBase64String(Data))
End With
End Sub
End Class
Then I just put a little non-IE detection (using the classic document.all check) in order to call the correct URL/set the correct SRC:
function updateCam() {
var url = (document.all) ? "../snapshot.cgi?t=" : "../cam.axd?t=";
url += new Date().getTime();
$.ajax({
type: "GET",
url: url,
timeout: 2000,
complete: function(xhr) {
try {
var src;
if(document.all)
src = (xhr.status == 200) ? url : '../i/cam-oos.jpg';
else
src = xhr.responseText;
$("#livePhoto").attr("src", src);
}
catch(e) {
JoshError.log(e);
}
camTimer = setTimeout(updateCam, 500);
}
});
}
It's very unfortunate I had to resort to this workaround for. I hate browser detection code, and I hate the additional load that is put on my server. The proxy will not only force me to waste more bandwidth, but it will not operate as efficiently because of the inherent proxy drawbacks and due to the time required to base-64 encode the image. Additionally, it is not setup to degrade as gracefully as IE. Although I could re-write the proxy to use HttpWebRequest and return the proper status codes, etc. I just wanted the easiest way out as possible because I am sick of dealing with this!
Thanks to all!
I believe the jquery will try to interpret the response from the server. I believe some browsers are more tolerant of the response interpretation so more restrictive browsers will fail because an image cannot be seen as HTML!
The solution to this would be to use a HEAD request type instead of a GET ( type: "HEAD" ). That way you will still get status responses back, without grabbing the image itself. Therefore the response will be empty (and shouldn't mess you up). Also, the response should be much faster.

Categories