Taywin
Posting Maven
2,633 posts since Apr 2010
Reputation Points: 275
Solved Threads: 375
Skill Endorsements: 17
ms_sws,
The only reliable way to test for file existance is to do it server-side in eg PHP, then build the page accordingly.
If server-side programming is not available, then all is not lost because images fire either an onload or an onerror event in response to their src being changed.
Hence, you can attempt to load your preferred image and if onerror fires, load your second preference. Then if onerror fires again go to next preference etc. etc. until eventually a default image is loaded - ie. an image you can guarantee exsits.
Here is one way to formulate the code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Airshow:: Cascading Image Preferences</title>
<style>
body { }
</style>
<script>
function cascade_preLoader(imgID) {
var imgElement = document.getElementById(imgID);
var basePath = 'gallery/';
var images = [ //Make this array as long or short as you like
'featured1.jpg',
'featured2.jpg',
'featured3.jpg',
'default.jpg'
];
var currentChoice = -1;
var preload = new Image();
preload.onload = function() {
if(imgElement) { imgElement.src = preload.src; }
};
preload.onerror = function() { loadNext(); };
var loadNext = function() {
if(++currentChoice < images.length){
preload.src = basePath + images[currentChoice];
}
};
loadNext();//attempt to preload first image
};
onload = function() {
cascade_preLoader('myImg');
};
</script>
</head>
<body>
<img id="myImg" src="gallery/default.jpg">
</body>
</html>
This is about as simple as I can make it. A productivity tool such as jQuery may be able to squeeze a few lines out of it but not too many(though I'm sure someone will try).
Airshow
Airshow
WiFi Lounge Lizard
2,782 posts since Apr 2009
Reputation Points: 370
Solved Threads: 388
Skill Endorsements: 9
You could actually use Ajax to test if file exist by calling the file on the server side. If the return status is not 200, the file does not exist. If you want to learn about Ajax, you can go http://www.w3schools.com/Ajax/Default.Asp. Hope this would give you another way to do.
Taywin
Posting Maven
2,633 posts since Apr 2010
Reputation Points: 275
Solved Threads: 375
Skill Endorsements: 17
Airshow
WiFi Lounge Lizard
2,782 posts since Apr 2009
Reputation Points: 370
Solved Threads: 388
Skill Endorsements: 9
Question Answered as of 3 Years Ago by
Airshow,
Taywin
and
ax8l