Preload images after page load with javascript & for loops

时间:2022-10-12 21:35:15

I am currently working on creating a webpage photo gallery. I have a ton of images I would like to preload with Javascript after page load. Rather than having a really, really long list of HTML links in my array, is it possible to utilize for loops? Please see my below code. Any helpful insights on what I'm doing wrong with the for loops would be very much appreciated! Thank you!!

我目前正在创建一个网页照片库。我有大量的图片,我想在页面加载后用Javascript预加载。我的数组中没有真正的,非常长的HTML链接列表,是否可以使用for循环?请看下面的代码。任何有用的见解我对for循环的错误将非常感谢!谢谢!!

<script type="text/javascript">
    function preloader() {
        var images = new Array()
        function preload() {
            for (i = 0; i < preload.arguments.length; i++) {
                images[i] = new Image()
                images[i].src = preload.arguments[i]
            }
        }
        preload(
            var i=1;
            "http://example.com/images/gallery/elephants-" + for (i=1;i<=5;i++) {document.write(i);} + ".jpg",
            "http://example.com/images/gallery/penguins-" + for (i=1;i<=2;i++) {document.write(i);} + ".png"
        )
    }

    function addLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                if (oldonload) {
                    oldonload();
                }
                func();
            }
        }
    }
    addLoadEvent(preloader);
</script>

The part I'm having a problem with is the for loops in the preload() section. The preload() section should output/do this:

我遇到问题的部分是preload()部分中的for循环。 preload()部分应输出/执行此操作:

preload(
    "http://example.com/images/gallery/elephants-1.jpg",
    "http://example.com/images/gallery/elephants-2.jpg",
    "http://example.com/images/gallery/elephants-3.jpg",
    "http://example.com/images/gallery/elephants-4.jpg",
    "http://example.com/images/gallery/elephants-5.jpg",
    "http://example.com/images/gallery/penguins-1.png",
    "http://example.com/images/gallery/penguins-2.png"
)

2 个解决方案

#1


2  

You can't concatenate a string and a loop together. You'll have to build an array of strings using a loop and the push method:

您不能将字符串和循环连接在一起。你必须使用循环和push方法构建一个字符串数组:

var i, urls = [];
for(i = 1; i <= 5; i++)
    urls.push('http://example.com/images/gallery/elephants-' + i + '.jpg');
for(i = 1; i <= 2; i++)
    urls.push('http://example.com/images/gallery/penguins-' + i + '.jpg');

Then use apply to call the preload function and pass in that array as the arguments:

然后使用apply调用preload函数并将该数组作为参数传入:

preload.apply(null, urls);

So your whole preloader function becomes:

所以你的整个预加载器功能变为:

function preloader() {
    var images = new Array()
    function preload() {
        for (i = 0; i < preload.arguments.length; i++) {
            images[i] = new Image()
            images[i].src = preload.arguments[i]
        }
    }

    var i, urls = [];
    for(i = 1; i <= 5; i++)
        urls.push('http://example.com/images/gallery/elephants-' + i + '.jpg');
    for(i = 1; i <= 2; i++)
        urls.push('http://example.com/images/gallery/penguins-' + i + '.jpg');

    preload.apply(null, urls);
}

#2


0  

You've defined a preload function that takes zero arguments, yet you are trying to pass in multiple arguments into the preload function. Additionally, you're using semicolons to separate the parameters instead of the required commas.

你已经定义了一个带有零参数的预加载函数,但是你试图将多个参数传递给preload函数。此外,您使用分号分隔参数而不是所需的逗号。

To accomplish this, I would suggest modifying your preload function to take a single array object that you can then iterate through, regardless of how many parameters are passed into the function. Below is a sample function definition:

为了实现这一点,我建议修改预加载函数以获取单个数组对象,然后无论有多少参数传递到函数中,都可以迭代。下面是一个示例函数定义:

function preload(arr) {
    for(var i = 0; i < arr.length; i++) {
        var img = document.createElement("img");
        img.setAttribute("style","display:none");
        img.setAttribute("src",arr[i]);
        document.body.appendChild(img);
    }
}

To use the function, you would pass in an array of URLs into the preload function using JavaScript object notation to represent the array.

要使用该函数,您可以使用JavaScript对象表示法将一组URL传递到preload函数中以表示该数组。

preload( 
    [ 
        "/images/first.png",
        "/images/second.png",
        "/images/third.png"
    ]
);

This array contains 3 strings, and each of the 3 strings will be passed into the src attribute of a separate, hidden image tag.

此数组包含3个字符串,3个字符串中的每一个都将传递到单独的隐藏图像标记的src属性中。

My only disclaimer with my specific example is that certain versions of IE may or may not cache hidden images. Whenever you work with raw JavaScript, as opposed to a library like jQuery, you'll need to thoroughly test in every browser to make sure that the solution is cross-compatible. Perhaps you can simply modify your function to accept the correct parameters and then use your existing techniques to preload the images, assuming yours is a tried and tested solution that you know works in all browsers you plan to support.

我的唯一免责声明是我的某些版本的IE可能会或可能不会缓存隐藏的图像。无论何时使用原始JavaScript,而不是像jQuery这样的库,您都需要在每个浏览器中进行彻底测试,以确保解决方案是交叉兼容的。也许您可以简单地修改您的函数以接受正确的参数,然后使用您现有的技术来预加载图像,假设您的图像是经过试验和测试的解决方案,您知道它可以在您计划支持的所有浏览器中使用。

#1


2  

You can't concatenate a string and a loop together. You'll have to build an array of strings using a loop and the push method:

您不能将字符串和循环连接在一起。你必须使用循环和push方法构建一个字符串数组:

var i, urls = [];
for(i = 1; i <= 5; i++)
    urls.push('http://example.com/images/gallery/elephants-' + i + '.jpg');
for(i = 1; i <= 2; i++)
    urls.push('http://example.com/images/gallery/penguins-' + i + '.jpg');

Then use apply to call the preload function and pass in that array as the arguments:

然后使用apply调用preload函数并将该数组作为参数传入:

preload.apply(null, urls);

So your whole preloader function becomes:

所以你的整个预加载器功能变为:

function preloader() {
    var images = new Array()
    function preload() {
        for (i = 0; i < preload.arguments.length; i++) {
            images[i] = new Image()
            images[i].src = preload.arguments[i]
        }
    }

    var i, urls = [];
    for(i = 1; i <= 5; i++)
        urls.push('http://example.com/images/gallery/elephants-' + i + '.jpg');
    for(i = 1; i <= 2; i++)
        urls.push('http://example.com/images/gallery/penguins-' + i + '.jpg');

    preload.apply(null, urls);
}

#2


0  

You've defined a preload function that takes zero arguments, yet you are trying to pass in multiple arguments into the preload function. Additionally, you're using semicolons to separate the parameters instead of the required commas.

你已经定义了一个带有零参数的预加载函数,但是你试图将多个参数传递给preload函数。此外,您使用分号分隔参数而不是所需的逗号。

To accomplish this, I would suggest modifying your preload function to take a single array object that you can then iterate through, regardless of how many parameters are passed into the function. Below is a sample function definition:

为了实现这一点,我建议修改预加载函数以获取单个数组对象,然后无论有多少参数传递到函数中,都可以迭代。下面是一个示例函数定义:

function preload(arr) {
    for(var i = 0; i < arr.length; i++) {
        var img = document.createElement("img");
        img.setAttribute("style","display:none");
        img.setAttribute("src",arr[i]);
        document.body.appendChild(img);
    }
}

To use the function, you would pass in an array of URLs into the preload function using JavaScript object notation to represent the array.

要使用该函数,您可以使用JavaScript对象表示法将一组URL传递到preload函数中以表示该数组。

preload( 
    [ 
        "/images/first.png",
        "/images/second.png",
        "/images/third.png"
    ]
);

This array contains 3 strings, and each of the 3 strings will be passed into the src attribute of a separate, hidden image tag.

此数组包含3个字符串,3个字符串中的每一个都将传递到单独的隐藏图像标记的src属性中。

My only disclaimer with my specific example is that certain versions of IE may or may not cache hidden images. Whenever you work with raw JavaScript, as opposed to a library like jQuery, you'll need to thoroughly test in every browser to make sure that the solution is cross-compatible. Perhaps you can simply modify your function to accept the correct parameters and then use your existing techniques to preload the images, assuming yours is a tried and tested solution that you know works in all browsers you plan to support.

我的唯一免责声明是我的某些版本的IE可能会或可能不会缓存隐藏的图像。无论何时使用原始JavaScript,而不是像jQuery这样的库,您都需要在每个浏览器中进行彻底测试,以确保解决方案是交叉兼容的。也许您可以简单地修改您的函数以接受正确的参数,然后使用您现有的技术来预加载图像,假设您的图像是经过试验和测试的解决方案,您知道它可以在您计划支持的所有浏览器中使用。