使用 JS 或 CSS 一次加载所有背景图像?

发布于 2024-11-03 09:42:47 字数 1117 浏览 0 评论 0原文

所以现在我有一个包含很多设施的列表。这些设施中的每一个都有一个 image 属性,它只是其图像文件的名称。例如,facility.image == 'YogisBarAndGrill'。在页面加载时,我通过 JSON 发送了一个字符串数组(图像名称),并尝试在显示页面和/或文本之前加载所有图像。

不幸的是,我所有的努力都没有效果,预加载不起作用。目前,以下内容在 document.ready() 之前执行

(function() {
  var imagesPath, serviceURL, urlSegs;
  urlSegs = window.location.pathname.split("/");
  serviceURL = imagesPath = '';
  if (urlSegs.length === 2) {
    serviceURL = urlSegs[1] + '_images';
    imagesPath = urlSegs[1] === 'places' ? 'images/logos/' : 'images/categories/';
    $.getJSON(serviceURL, function(imageNames) {
      var i, _results;
      _results = [];
      for (i in imageNames) {
        if (i < imageNames.length) {
          _results.push((new Image()).src = imagesPath + imageNames[i] + '.png');
        }
      }
      return _results;
    });
  }
}).call(this);

。每个列表图像的 css 如下所示: background-image: url('images/logos/YogisBarAndGrill.png')< /code> 或类似的东西。

无论如何 - 我上面发布的内容不起作用。不进行预加载。我想要实现的是立即显示所有图像或者更好的是让页面什么都不显示,直到所有图像加载完毕。

感谢您的帮助!

So right now I have a list with a bunch of Facilities. Each of these facilities has an image property which is simply just the name of it's image file. For example, facility.image == 'YogisBarAndGrill'. On pageload, I sent an array of strings (image names) via JSON and try to load all the images before the page and/or text is displayed.

Unfortunately, all my efforts are to no avail and the preloading doesn't work. Currently, the following is executed before document.ready()

(function() {
  var imagesPath, serviceURL, urlSegs;
  urlSegs = window.location.pathname.split("/");
  serviceURL = imagesPath = '';
  if (urlSegs.length === 2) {
    serviceURL = urlSegs[1] + '_images';
    imagesPath = urlSegs[1] === 'places' ? 'images/logos/' : 'images/categories/';
    $.getJSON(serviceURL, function(imageNames) {
      var i, _results;
      _results = [];
      for (i in imageNames) {
        if (i < imageNames.length) {
          _results.push((new Image()).src = imagesPath + imageNames[i] + '.png');
        }
      }
      return _results;
    });
  }
}).call(this);

The css for each list image looks like the following: background-image: url('images/logos/YogisBarAndGrill.png') or something similar.

Anyways - what I posted above doesn't work. No preloading is done. What I'm looking to achieve is having all images display at once OR even better would be to have the page display nothing at all until all images are done loading.

Thanks for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

静谧幽蓝 2024-11-10 09:42:47

当您说预加载“不起作用”时,您的意思是什么?您预计会发生什么?

“预加载”的意思是“在需要之前加载”。如果具有这些背景图像的 HTML 元素与您正在使用的 JavaScript 位于同一页面上,那么浏览器将在解析 CSS 后立即下载它们,这在 JavaScript 停止运行后不太可能持续很长时间。

When you say the preloading “doesn’t work”, what do you mean? What do you expect to happen?

“Preloading” means “loading before you need”. If the HTML elements that have these background images are on the same page as the JavaScript you’re using, then the browser will be downloading them as soon as it’s parsed the CSS, which is unlikely to be noticeably long after the JavaScript has stopped running.

不甘平庸 2024-11-10 09:42:47

您可以通过为要加载的每个图像动态创建 元素来完成此操作,让它们完成加载,然后将 background-image 设置为相同的 url。在演示中,我每次运行时都使用随机图像,因此不会缓存它们。

演示: http://jsfiddle.net/ThinkingStiff/Mp2cj/

脚本:

function loadImages() {

    var images = getImages( 5 ),
        imgs = [],
        loaded = 0;

    createImgs();

    var timer = window.setInterval( function () {
        if( loaded == images.length ) {
            window.clearInterval( timer );
            setImages();
        };
    }, 50 );

    function createImgs() {
        for( var index = 0; index < images.length; index++ ) {
            imgs.push( document.createElement( 'img' ) );
            imgs[index].onload = function () { loaded++; };
            imgs[index].src = images[index];
        };
    };

    function setImages() {
        var divs = document.querySelectorAll( '#container div' );

        for( var index = 0; index < divs.length; index++ ) {
            divs[index].style.backgroundImage = 'url(' + images[index] + ')';
            console.log( 'div' );            
        };

        document.getElementById( 'container' ).removeAttribute( 'class' );
        document.getElementById( 'loading' ).setAttribute( 'class', 'hide' );
    };

    function getImages( count ) {
        var images = [],
            url = 'http://placekitten.com/';

        for( var index = 0, width, height; index < count; index++ ) {
            width = Math.floor( Math.random() * ( 1000 - 500 + 1 ) ) + 500;
            height = Math.floor( Math.random() * ( 1000 - 500 + 1 ) ) + 500;
            images.push( url + width + '/' + height );
        };

        return images;
    };

};

loadImages();

HTML:

<div id="loading">images loading...</div>
<div id="container" class="hide">
    <div></div><div></div><div></div><div></div><div></div>
</div>​

CSS:

.hide {
    display: none;
}

#container div {
    background-size: 100px 100px;
    display: inline-block;
    height: 100px;
    width: 100px;    
}​

You can do this by dynamically creating <img> elements for each image you want to load, let them complete their loading, then set background-image to the same urls. In the demo I use random images each run so they aren't cached.

Demo: http://jsfiddle.net/ThinkingStiff/Mp2cj/

Script:

function loadImages() {

    var images = getImages( 5 ),
        imgs = [],
        loaded = 0;

    createImgs();

    var timer = window.setInterval( function () {
        if( loaded == images.length ) {
            window.clearInterval( timer );
            setImages();
        };
    }, 50 );

    function createImgs() {
        for( var index = 0; index < images.length; index++ ) {
            imgs.push( document.createElement( 'img' ) );
            imgs[index].onload = function () { loaded++; };
            imgs[index].src = images[index];
        };
    };

    function setImages() {
        var divs = document.querySelectorAll( '#container div' );

        for( var index = 0; index < divs.length; index++ ) {
            divs[index].style.backgroundImage = 'url(' + images[index] + ')';
            console.log( 'div' );            
        };

        document.getElementById( 'container' ).removeAttribute( 'class' );
        document.getElementById( 'loading' ).setAttribute( 'class', 'hide' );
    };

    function getImages( count ) {
        var images = [],
            url = 'http://placekitten.com/';

        for( var index = 0, width, height; index < count; index++ ) {
            width = Math.floor( Math.random() * ( 1000 - 500 + 1 ) ) + 500;
            height = Math.floor( Math.random() * ( 1000 - 500 + 1 ) ) + 500;
            images.push( url + width + '/' + height );
        };

        return images;
    };

};

loadImages();

HTML:

<div id="loading">images loading...</div>
<div id="container" class="hide">
    <div></div><div></div><div></div><div></div><div></div>
</div>​

CSS:

.hide {
    display: none;
}

#container div {
    background-size: 100px 100px;
    display: inline-block;
    height: 100px;
    width: 100px;    
}​
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文