Polymer 1.0+ iron-image - 等待图像文件存在以避免 404 错误的最佳实践

Polymer 1.0+ iron-image - best practice to wait for existence of image file to avoid 404 error

我想知道 polymer 1.0+ 中的最佳实践是什么,使用 iron-image 加载由另一个后端异步进程生成的文件。我希望 iron-image 等待后端进程完成创建图像文件,并显示占位符图像,直到它可以加载。目前,当后端进程仍在生成图像时,我间歇性地收到 404 错误。

在过去,我会在计时器间隔内执行类似下面的 js 函数的操作...但我相信一定有更好的方法,并且没有被弃用(同步 XMLHttpRequest on the main thread 已被弃用,因为它对最终用户的体验有不利影响)。

imageExists: function(image_url) {
     var http = new XMLHttpRequest();

     http.open('HEAD', image_url, false);
     http.send();

     return http.status != 404;
},

是否有我没有利用来处理这种情况的 iron-image 内置功能?

您可以通过添加铁-ajax 轻松完成此操作。使用 iron-ajax 来处理图像请求,同时在组件中传递或明确定义占位符图像(正如我在示例中所做的那样)。成功后,您将新图像注入组件。

https://jsfiddle.net/devappended2/hwrg1sdu/

<dom-module id="my-component">
    <template>
     <iron-ajax
      auto
            url="{{url}}"
            on-response="_imageResponse"
        </iron-ajax>
        <iron-image sizing="contain" preload fade src="{{image}}"></iron-image>
    </template>
</dom-module>
<script>
Polymer({
    is: 'my-component',
    properties: {
        image: {
         type:   String,
         value:   'path/placeholder.jpg'
        }
    },
    _imageResponse: function(e, detail){
     this.image = detail;
    }
});
</script>

您可以使用 placeholder 属性:

/**
 * This image will be used as a background/placeholder until the src image has
 * loaded.  Use of a data-URI for placeholder is encouraged for instant rendering.
 */
placeholder: {
  type: String,
  value: null,
  observer: '_placeholderChanged'
},

样本:

<iron-image style="width:400px; height:400px;" placeholder="./loading.png"
      sizing="cover" preload src="http://lorempixel.com/600/400"></iron-image>