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">');
}
});
Related
I'm working on a swipe-able wine image viewer for NapaWapa.com and I've got it working pretty well: http://www.tonyjacobson.com/napawapa/gallery/index.html
I'm using a jquery plugin to read the exif data of the images in the gallery. However, the plugin seems to only work when the src attribute is hard coded — not when the images are loaded via AJAX. Can any of you experts out there take a peek at the JS (http://www.tonyjacobson.com/napawapa/gallery/js/jquery.exif.js) to see if you could recommend a change to the plugin code to recommend a fix?
Here's the specific part of the plugin code where it deals with reading the EXIF data:
// HTML IMG EXAMPLE
<img class="lazyOwl" data-src="images/03.jpg" exif="true" />
// JAVASCRIPT CLICK TO TEST IMG EXIF DATA
$("img").on('click', function(event){
$(this).exifLoad();
console.log( "HIT: " + $(this).exif('Make') );
});
// JQUERY PLUGIN CODE EXCERPT
function loadAllImages()
{
var aImages = document.getElementsByTagName("img");
for (var i=0;i<aImages.length;i++) {
if (aImages[i].getAttribute("exif") == "true") {
if (!aImages[i].complete) {
addEvent(aImages[i], "load",
function() {
EXIF.getData(this);
}
);
} else {
EXIF.getData(aImages[i]);
}
}
}
}
// automatically load exif data for all images with exif=true when doc is ready
jQuery(document).ready(loadAllImages);
// load data for images manually
jQuery.fn.exifLoad = function(fncCallback) {
return this.each(function() {
EXIF.getData(this, fncCallback)
});
}
I was searching for a similar question, and found assistance from this thread. Try modifying your Javascript (not the plugin) to include this code:
$("img").load(function() {
$(this).exifLoad(function() {
// exif data should now be ready...
});
});
I am looking for a way to asynchronously load an image with javascript/jquery while, at the same time, be able to handle a returning xml document (in case of an error).
At the moment I load the image like this:
var img = $("<img id='ws-image'/>").attr('src', $("#dynImgUrl").val());
img.load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined"
|| this.naturalWidth == 0) {
alert('broken image!');
} else {
img.attr('width', 500);
img.attr('height', 500);
$("img-div").html(img);
}
}).error(function() {
alert("Could not load image");
});
This does work as long as the server returns an image. If, in case of an error, it returns a xml document, the error callback is called. But I need to get the content of that xml document and don't know how.
Is there a way to be able to handle both types of possible server responses?
Thank you!
Assuming the server has CORS enabled to allow cross-domain Ajax, I would attempt to load the image, and then do an Ajax fetch for the same resource if the image load fails.
Alternatively, if a second pass to the server is unacceptable, you could do a fetch of the resource, encode it in base 64 (using btoa) and show the image from a data: URI. Then, do the same error-checking you do here, and refer back to the original Ajax result in the event of image failure.
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.
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}
/>
)
}
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.