【问题标题】:Load images during page startup在页面启动期间加载图像
【发布时间】:2012-09-08 19:06:02
【问题描述】:

我目前正在使用单选按钮和复选框来根据值显示图像。我注意到图像在开始时加载缓慢。例如,已经使用“display:none”(已经设置了它们的 src 属性)预先创建了图像元素,所以我唯一要做的就是使用 display 属性。是否可以预加载图像? 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>

【问题讨论】:

    标签: javascript


    【解决方案1】:

    是的!如果你有 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/

    【讨论】:

    • 显然,对标记为 JavaScript 的问题发布基于 JQuery 的答案被认为是错误的 S.O 形式。另外,Img 标签的选择器不是 $('img') 吗?
    【解决方案2】:

    这是我前段时间为自己制作的一个函数: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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多