繁体   English   中英

在页面启动期间加载图像

[英]Load images during page startup

我目前正在使用单选按钮和复选框来显示基于值的图像。 我注意到图像开始时加载缓慢。 例如,使用“ display:none”(已经设置了src属性)预先创建了图像元素,那么我要做的唯一事情就是使用display属性。 是否可以预加载图像?

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>

是! 如果您有JQuery,则预加载图像真的很容易:

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

$(['some-image.gif']).preload();

还要检查此资源: http : //perishablepress.com/3-ways-preload-images-css-javascript-ajax/

这是我前一段时间为自己创建的功能: http : //pastebin.com/GeBawE8r

您可以按以下方式使用它:

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();

加载完成后, ready属性将设置为true,您可以访问list对象中的图像。

if(loader.ready)
    alert(loader.list.myImageName); // Image object

http://jsfiddle.net/uttZw/1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM