Javascript 如何防止从服务器端加载映像
我有带图像的API数据,但由于互联网问题或其他原因,图像需要花费太多时间才能完全加载 是否有任何方法可以防止这种加载,因为当加载所有数据并且图像仍需要时间显示时,它看起来很糟糕 menu.htmlJavascript 如何防止从服务器端加载映像,javascript,html,angular,ionic-framework,Javascript,Html,Angular,Ionic Framework,我有带图像的API数据,但由于互联网问题或其他原因,图像需要花费太多时间才能完全加载 是否有任何方法可以防止这种加载,因为当加载所有数据并且图像仍需要时间显示时,它看起来很糟糕 menu.html <ion-card class="categories_item" *ngFor="let category of categories; let i = index;"> <ion-grid> <ion-row> <ion-col s
<ion-card class="categories_item" *ngFor="let category of categories; let i = index;">
<ion-grid>
<ion-row>
<ion-col size-md="2" size="4" class="img-zoom" align-self-center>
<img [src]="category?.Picture1" (click)="imgView(category?.Picture1)" id="imgClickAble"
class="imgClickAble" />
.....
</ion-col>
<ion-col size-md="9" size="6" (click)="goToitemCategory(category.ID)">
.....
</ion-col>
</ion-row>
</ion-grid>
</ion-card>
.....
.....
我需要显示其他内容,直到像占位符一样加载完整图像,或者我想缓存图像以备将来使用。您可以隐藏原始图像并在循环中使用占位符图像,然后调用原始图像
onload
函数隐藏占位符图像并显示实际图像
<img src="placeholderurl" id="placeholder_{{i}}" >
<img [src]="category?.Picture1" class="hidden" id="original_{{i}}" (load)="onImageLoad(i)">
我创建了一个stackblitz项目: 首先,创建一个自定义指令。在构造函数中,插入
img
标记的ElementRef
,并将默认值设置为src
属性
然后在OnInit
回调中,创建一个new Image()
并设置新的源。在onload
回调中,将新源设置为ElementRef
到img
标记
希望这有帮助
这是指令:
import { Directive, ElementRef, Input,Renderer2, OnInit} from '@angular/core';
@Directive({
selector: '[appDynamicImage]'
})
export class DynamicImageDirective implements OnInit {
@Input()
dynamicSrc: string;
private defaultSrc = 'https://via.placeholder.com/500x300';
constructor(private elem: ElementRef,
private renderer: Renderer2) {
this.setSource(this.defaultSrc);
}
ngOnInit(){
setTimeout(() => { // just to mock loading time
this.setAsyncSource(this.dynamicSrc);
},2000)
}
setAsyncSource = (src: string) => {
const dynamicImage = new Image();
dynamicImage.onload = (e) => {
console.log('onload', e)
this.setSource(src);
}
dynamicImage.onerror = (e) => {
console.log('Error happened', e)
}
dynamicImage.src = src;
}
setSource = (src: string) => {
this.renderer.setAttribute(this.elem.nativeElement,'src',src);
}
}
这是模板:
<img appDynamicImage [dynamicSrc]="'https://www.fillmurray.com/640/360'"/>
您可以为img
标记创建自定义指令。当从API调用接收到图像的URL时,您可以使用new image()
创建一个新图像,并且在onload
回调中,您可以替换src
属性。我建议在从API获取img时将某种标志设置为true,默认情况下需要为false。然后在模板中使用*ngIf show隐藏占位符div和图像conditionally@AkshayBhat它只能帮助隐藏或取消隐藏占位符,但无助于图像加载speed@HarunYilmaz你能给我举个例子吗?那就是helpful@Waqarali我发布了一个工作示例作为答案。我已经尝试过了,但它不起作用,它显示了两个图像(占位符和原始图像)查看链接。我只是需要预防loading@Waqarali您是否在css中添加了.hidden
类您必须添加.hidden{display:none}
<img appDynamicImage [dynamicSrc]="'https://www.fillmurray.com/640/360'"/>