I use the following code to refresh an image in the browser. I just want to modify the code in order to first check if the image exists and then display the image. If the image does not exist I will only refresh the image to the previous version of the picture. Can someone point me how to accomplish this using javascript or jquery?
<html>
<head>
<script language="JavaScript">
function refreshIt(element) {
setTimeout(function() {
element.src = element.src.split('?')[0] + '?' + new Date().getTime();
refreshIt(element);
}, 500); // refresh every 500ms
}
</script>
</head>
<body>
<img src="swt.png" name="myCam" onload="refreshIt(this)">
</body>
</html>
Edited: I need a combination of the already implemented functionality plus the file checking.
Functionality:
if image exist
refresh image
else
show cached image
Something like this:
$('#image_id').error(function() {
alert('Image does not exist !!');
});
Related
I have an html link 'localurl' pointing to an URL of an image (for example the current album artwork of the music playing on my sonos), so that when I give 'localurl' in my browser, it doesn't display the image directly but a path like 'http://image.png'. This last path links to the image.
I would like to display this image in an HTML file using the 'localurl'. I think it should look something like this:
<!DOCTYPE html>
<html>
<body >
<img src=getUrlFromHTML('localurl') >
<script type="text/javascript">
function getUrlFromHTML(url)
{
...
}
</script>
</body>
</html>
EDIT: the link 'http://image.png' is not always the same, I don't know it in advance, this is why in need to go with 'localurl'. The concept is the following: I have an openHAB installation with the Sonos Binding, I have a string item called Sonos_CurrentAlbumArtUrl and through the API of openHAB, i get the link http://openhab.local:8080/rest/items/Sonos_CurrentAlbumArtUrl/state (this is my 'localurl' and it is pointing to 'http://image.png' which depends on the music being played on the Sonos (using Spotify). I hope this is a bit more clear.
unless you want to refer selected files from <input type=file you dont need to use javascript.
you can just write the location. For locations you can drag image to your browser, copy from the address bar.
<img src="file:///C:/Users/nerkn/Documents/cobokin.jpg"
I took the time to learn some javascript and I found an answer that fits to my need. I share here the content of the HTML-body as I think it could help others.
<body>
<img id="SonosAlbumArt">
<script type="text/javascript">
var link = 'http://openhab.local:8080/rest/items/Sonos_CurrentAlbumArtUrl/state';
var img = document.getElementById('SonosAlbumArt');
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', function () { refreshAlbumArt()} );
function sendAlbumArtRequest() {
xhr.open('GET', link);
xhr.send(null);
}
function refreshAlbumArt() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
img.src = xhr.responseText;
}
}
setInterval(sendAlbumArtRequest, 1000);
</script>
</body>
I am not quite convinced that the setInterval is the best way to do it. I miss something like an event triggered when the album art changes, in order to not send requests each second. Any suggestions are welcome.
Well, the title pretty much describes my question:
How to load the background-image dynamically after it has been fully loaded? Sometimes, I must use backgrounds that are so big that it can take a while for the browser to download it. I'd rather 'load it in the background' and let it fade in when it has been fully loaded.
I think jQuery would be best to be using, but I also want my background to appear if JavaScript has been disabled. If this really isn't possible, so be it, but I think it is?
Best regards,
Aart
........
EDIT:
Thanks a bunch, guys! I've been bugged with this for ages and just couldn't think of a nice and easy way.
I converted Jeffrey's Javascript-solution into a jQuery one, just because jQuery's built-in fade looks so awesome.
I'll just post it here in case anyone else has the same issue:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('#img').css('opacity','0').load(function() {
$(this).animate({
opacity: 1
}, 500);
});
});
</script>
<img src='yourimage.jpg' id='img'/>
If the image is included with an img element:
<img src="bg.jpg" id="img" onload="this.style.opacity='1'">
<script>
document.getElementById("img").style.opacity="0";
</script>
That should load the image normally if JavaScript is disabled, but show it only once it loads assuming it's enabled.
One thing to note (that I overlooked): some browsers will not even attempt to load an image if its display property is none. That's why this method uses the opacity attribute.
You can't do it when JS is disabled. However, what you can do is set the background image in CSS and then use the following script (assuming the element has the ID myelem).
(function() {
var elm = document.getElementById('myelem'),
url = 'background image URL here';
elm.style.backgroundImage = "none";
var tmp = new Image();
tmp.onload = function() {
elm.style.backgroundImage = "url('"+url+"')";
// or insert some other special effect code here.
};
tmp.src = url;
})();
EDIT: Although, make sure your background images are optimal. If they are PNG, try having them Indexed with as small a colour table as possible, or make sure the alpha channel is removed if there is no transparency. If they are JPEG, try adjusting the compression.
Check the example on this page:
http://www.w3schools.com/jsref/event_img_onload.asp
Using "image.onload" will start your code only when the image is ready
Without javascript you can't have events, so you won't be able to know if the image is loaded, at least for the first rendering.
You can also use a css preload (put the image as a background in a hidden div), but that would work better in your first refresh and not while loading.
You can set a variable to the image, and when it loads, set it to the body background:
var my_bg = new Image();
my_bg.src = "url(mybackground.png)";
document.style.backgroundImage = my_bg;
What you are looking for is an image onLoad method. If you set the image with a display:none it wont be visible. To get around the possible lack of javascript, you do the following:
<body style="background-image:url(image.png);">
<img src="image.png" style="display:none" onLoad="changeBackground();" />
</body>
<script>
document.body.style.backgroundImage = "";
function changeBackground(){
document.body.style.backgroundImage = "url(image.png)";
}
</script>
This way, if javascript isnt enabled, the bg will load as normal. If it is, it will display at the end
I have an image that is being constantly updated from a local webcam source, it is then displayed on a website. I can get the image to show and by refreshing the page the image will update (obviously).
What I am wondering is, how can I update this image every (lets say) 5 seconds, without having to refresh the page manually (ie. utilizing ajax).
Basic things I am not too sure about:
<img src=""/> <--- how can I load an image url that is located within the javascript code
within the javascript code, how can I create a function that will automatically update the image source, without having to reload the page
As I understand it, upon reading around, one of the main problems is that browsers will load the cached image unless the resulting httprequest looks different each time, as such am I required to add an additional item within the url string (ie. www.yoursire.com?image=foo&date=bar (the date is grabbed by date function or some other iterated value)) in order to circumvent this horrible browser predisposition?
Thanks in advance!
Without writing all the code
look at the javascript functions setTimeout() and setInterval()
it's easy to change the src attribute of ana element
document.getElementbyId("imageId").setAttribute("src", imageUrl);
if your image request url is the same everytime (but the pic has changed server-side) you can either add a "no-cache" to the ajax request header, or possibly add a random query string to the image to force a reload each time (e.g http://mydomain/myimage?3754854 )
With jQuery:
$(document).ready(function() {
window.setInterval("refreshCamera();", 1000); // one second interval
});
var url = 'http://www.x.com/abc?refresh=';
var forcerefresh = 0;
function refreshCamera()
{
forcerefresh = forcerefresh + 1;
$('#myImageId').attr('src',url + forcerefresh);
}
(the force refresh thing is to prevent browser from using locally cached image)
I have done this and it works using setting the image source. Also on the server-side, you have to send no-cache HTTP headers to prevent caching.
<img src="" id="webcam" />
<script type="text/javascript">
var int=self.setInterval("reload()",1000);
function reload(){
$("#webcam").attr("src", "/mysite/webcamImage");
}
</script>
You could use jquery to load an image object and then attach a timer and run the code for every 5 seconds.
Here's an example:
// when the DOM is ready
$(function () {
var img = new Image();
// wrap our new image in jQuery, then:
$(img)
// once the image has loaded, execute this code
.load(function () {
// set the image hidden by default
$(this).hide();
// with the holding div #loader, apply:
$('#loader')
// remove the loading class (so no background spinner),
.removeClass('loading')
// then insert our image
.append(this);
// fade our image in to create a nice effect
$(this).fadeIn();
})
// if there was an error loading the image, react accordingly
.error(function () {
// notify the user that the image could not be loaded
})
// *finally*, set the src attribute of the new image to our image
.attr('src', 'images/headshot.jpg');
});
Read more about this here:
http://jqueryfordesigners.com/image-loading/
About preventing the caching of dynamically loaded images you can just add the last modified timestamp in the url:
<img src="image.jpg?lastmodified=1291235678" ...
I had the same need, so I'm appending my own js solution below. Occasionally our webcam will be in the middle of writing the jpg to a directory when the ajax refresh occurs, so instead of displaying a broken image, I'm presenting an animated gif.
JS:
<script>
$(document).ready(function () {
(function () {
// show webcam jpg on initial page load
var refreshWebcam = function () {
// webcam link is appended with a timestamp to prevent caching
var webcamImg = 'http://abs_path_to_webcam_img/webcam1.jpg' + '?' + (new Date()).getTime();
var loadingImg = 'http://abs_path_to_webcam_loading_img.gif'
$.ajax({
url: webcamImg,
type: 'HEAD',
error: function () {
$('#refresh').attr('src', loadingImg);
//console.log('failed loading ' + webcamImg);
// if there's an error, retry loading image every half second
setTimeout(function () {
refreshWebcam();
}, 500)
},
success: function () {
$('#refresh').attr('src', webcamImg);
//console.log('successfully loaded ' + webcamImg);
}
});
};
// refresh webcam jpg every 5 seconds
window.setInterval(refreshWebcam, 5000);
refreshWebcam();
})();
});
HTML
<img alt="Web Camera Image" id="refresh" src="http://abs_path_to_webcam_loading_img.gif" />
Disabling caching will overwhelm your webcam (even good ones) if it gets popular
I tried allowing the image to be allowed to be cached for 6 seconds (Cache-Control: max-age=6), because I needed to prevent a webcam from being overwhelmed. The code that I was working with looked a bit like this, but it has a problem:
<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg" /><br />
<script type="text/javascript">
(function() {
setInterval(function() {
var myImageElement = document.getElementById('liveimage');
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg';
}, 6000);
}());
</script>
Previously, the web-developer had put a ?rand=(random-number) in as a cache-busting technique. That's bad when the image is cacheble (even if only for a short period of time), because if means that you may (depending on whether your cache will consider query parameters as non-cachable), mean you get a very poor cache hit rate and you get a lot of page representations being built up.
The problem was that the image was now not refreshing, because although the src attribute was being reassigned, it wasn't actually changing to a different value, so the browser (Chrome 51) wasn't updating the image. I changed the logic to have either an ?1 or a ?2 query string argument, and alternate between them.
<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg?1" /><br />
<script type="text/javascript">
(function() {
setInterval(function() {
var myImageElement = document.getElementById('liveimage');
if (myImageElement.src == 'http://example.com/webcams/suddenlypopular.jpg?1') {
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?2';
} else {
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?1';
}
myLogElement.innerHTML = myImageElement.src;
}, 6000);
}());
</script>
EDIT: While this works in Chrome and IE, it didn't work in Firefox, so I came up with an alternative solution that is working in Chrome, Firefox and IE (Safari is currently untested).
<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg" />
<script type="text/javascript">
(function() {
setInterval(function() {
var myImageElement = document.getElementById('liveimage');
var d = new Date();
// 6000 is 6 seconds; the desired refresh rate
// % n is a bit of an experiment for being nice on cache invalidation; it also puts a bound on how out-of-date something would be regarding clock skew.
var timeSlice = Math.floor(d.getTime() / 6000) % 3;
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?t=' + timeSlice;
}, 6000);
}());
</script>
So now I have a cache-friendly webcam that does update.
Apache reverse-proxy configuration
Here's a snippet from Apache httpd for how you might reverse-proxy a webcam to set a particular caching policy.
<Location /webcams/suddenlypopular.jpg>
ProxyPass http://mywebcamdevice.example.com/snapshot.jpg
ProxyPassReverse http://mywebcamdevice.example.com/snapshot.jpg
ExpiresByType image/jpeg "access plus 6 seconds"
Header unset ETag
Header unset Last-Modified
</Location>
I'm trying to write a simple javascript snippet which delays the image loading by a certain number of millisecs below.
<html>
<head>
<script type="text/javascript">
function SetTimer()
{
var Timer = setInterval("showImage()",3000);
}
function showImage()
{
document.getElementById('showImage').style.visibility = 'visible';
}
</script>
</head>
<body onLoad="SetTimer()" style="visibility:hidden">
<div id=showImage>
<img src="gwyneth_paltrow_2.jpg">
</div>
</body>
</html>
Am I approaching this incorrectly?
thanks in advance
This is basically an OK approach.
There are some bugs, namely:
document.getElementByID('showImage')style.visibility = 'hidden';
getElementByID should be getElementById
needs a dot after ('showImage')
You are setting the visibility to 'hidden' in order to show it. Instead, you should start out as hidden, and then make it appear instead of disappear.
document.getElementById('showImage').style.visibility = 'hidden';
Well, the code is backwards given the stated goal of delaying the appearance of the image. If I just use your code as a basis, then I would have the visibility of the image as hidden, using CSS, and then trigger the display to visible on the timer.
However, having said that... This doesn't delay the loading of the image, it merely delays the display of it. The other way to handle it is to use the timer to load an Image object in Javascript and then insert it into the DOM. This, then, will actually delay the loading of the image for 3 seconds. Something like this:
function showImage()
{
var myImage = new Image();
myImage.src = "gwyneth_paltrow_2.jpg";
document.getElementById("showImage").appendChild(myImage);
}
I'm doing that from memory, so syntax may not be entirely correct.
I need to have a function called after a larger image is loaded on the page. I've tried some various solutions that I've found on here and around the web, but none either fit or work. Here's what I've tried that seems to make the most sense...and this is using jQuery
var imgs = $('#bgStage img.bg'),
imgCnt = imgs.length,
cnt = 0;
imgs.load(function () {
cnt++;
if (imgCnt === cnt) {
homeSlider();
}
}).each(function () {
if (this.complete) {
$(this).trigger('load');
}
});
This doesn't seem to wait until the img.bg is loaded. The homeSlider() function is called and started as I still see the image still loading.
So, I am wondering how a browser determines an image is loaded? Is it when it can read the width and height? Because I am defining the width and height in the CSS for the image to force it to be a certain size.
If anyone has any insight as to what makes the onload event fire for an image, that'd be great! Thanks.
You can always check for $('img').length();
Here's a sample code that should work. I did a project that needed this and I remember that some problems might include:
The browser caches the image (IE i believe) so I had to append ?[random] at the end
Maybe you have to set the src javascriptly so that your event is hooked at the right time
Sample code:
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#imageSample')
.load(function(){
alert($('#imageSample').width());
alert($('#imageSample').height());
})
.attr('src', 'http://www.gimp.org/tutorials/Lite_Quickies/quintet_hst_big.jpg?' + new Date());
});
</script>
<style type="text/css"></style>
</head>
<body>
<img id="imageSample" src="" alt="" />
</body>
</html>
Images might be cached, try this: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js
Use something simple like so:
var loaded = false;
var len = $('#bgStage img.bg'), c = 0;
$('#bgStage img.bg').each(function(){
$(this).attr('src',$(this).attr('src') + new Date()); //Remove caching.
$(this).bind('onload',function(){
//Other Stuff here!
if(c == len)
{
HomeSlider();
}
c++; //Increment
});
});
Tell me how it goes :)
Each image has a complete property. Unfortunately not all browsers support it. They always report true, even if the image hasn't loaded at all. IE gets it right. ;-)
http://simon.html5.org/test/html/semantics/img/src/ (not mine)