I am currently working with radio buttons and check boxes to display images based on values. I am noticing that the images are loading slowly at the start. For example, Have pre-created the image elements with "display:none" (with their src attribute already set) so then the only thing I have to do is play with the display attribute. Is there away to preload the images? EXAMPLE
JS
<script>
function check_value(currentElement, val, id, type) {
var el = document.getElementById("imgBox" + id);
if (val > 0 && val < 4) { //will trigger when [1,2,3]
if(currentElement.checked)
{
el.src = "images/" + type + val + ".jpg";
el.style.display = "";
}
else
{
el.src = "";
el.style.display = "none";
}
}
}
</script>
HTML
<h2>Choose a bike</h2>
<form name="builder">
<input type="radio" name="field" onclick='check_value(this, 1, 1, "bike")'/> KAWASAKI KX 450F<br />
<input type="radio" name="field" onclick='check_value(this, 2, 1, "bike")'/> 2010 Yamaha Road Star S<br />
<input type="radio" name="field" onclick='check_value(this, 3, 1, "bike")'/> Aprilia RSV4<br />
</form>
Yes! Preloading images is really easy if you have JQuery:
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
$(['some-image.gif']).preload();
Also check this resource: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
Here is a function I've made for myself some time ago: http://pastebin.com/GeBawE8r
You can use it as follows:
var loader = new imagePreloader();
// Object containing the names of the imgs as keys and url as values
loader.list = {name: "url"...};
// function to call when done loading everything
loader.onload = ...
// function to call at each time it loades a single image of the list
loader.each = ...
// function to call when unable to load one of the images
loader.onerror = ...
// set this to true to continue even if some of the images fail to load
loader.ignoreErrors = true/false
// Starts loading the images
loader.load();
After it's done loading the property ready
will be set to true and you can access the images in the list
object.
if(loader.ready)
alert(loader.list.myImageName); // Image object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.