我正在使用 JavaScript 和 jQuery 编写我的网站,但我遇到了以下问题。
我只想让线程休眠并显示加载动画,直到 promise 对象完全加载到我的网站中。
我不知道该怎么做,有人可以帮忙吗?
@A.沃尔夫 因为我在使用 PDF.JS 插件时遇到了这个问题。我正在尝试在其之上声明一个自定义类。
下面是我自定义的类
function WhiteBoardPdf3(canvasContext,url){
this.canvasContext=canvasContext;
this.url=url;
this.pdfOriPromise=PDFJS.getDocument(url);
this.pdfPromise=Promise.cast(this.pdfOriPromise);
this.pdfDoc=null;
/*----Here is the problem------*/
this.pdfPromise.then(function getPdf(_pdfDoc){
this.pdfDoc=_pdfDoc
});
/*----------------------------*/
this.pageNum=1;
this.scale=1;
this.renderPage(1);
}
WhiteBoardPdf3.prototype.getPdfPromise=function(){
return this.pdfPromise;
}
WhiteBoardPdf3.prototype.renderPage=function(){
var num=this.pageNum;
var scale=this.scale;
var canvasContext=this.canvasContext;
var canvas=canvasContext.canvas;
var canvasClassName=canvas.className;
var allCanvas=document.getElementsByClassName(canvasClassName);
var canvasContainer=document.getElementById("whiteBoardLayerContainer");
this.pdfPromise.then(function getPdf(_pdfDoc){
_pdfDoc.getPage(num).then(function(page){
var viewport=page.getViewport(scale);
for(var i=0;i<allCanvas.length;i++){
allCanvas[i].height=viewport.height;
allCanvas[i].width=viewport.width;
}
canvasContainer.style.width=viewport.width+'px';
var renderContext={
canvasContext: canvasContext,
viewport: viewport
}
page.render(renderContext);
});
});
}
WhiteBoardPdf3.prototype.getPdfNumOfPages=function(){
this.pdfDoc.numPages;
}
PDFJS.getDocument(url) 将返回一个 promise 对象。
但是,问题是当我构造这个类并在主程序中调用getPdfNumOfPages() 函数时。我注意到程序将在“pdfDoc”( promise 对象)完成加载之前调用 getPdfNumOfPages() 函数。所以我想在 promise 对象完成加载之前让线程休眠并显示加载动画。因此,getPdfNumOfPages() 函数将在“pdfDoc”加载后运行。
最佳答案
好吧,您可以在发送 ajax 请求之前在您的页面上显示加载图像,并在收到响应后隐藏它。
HTML 代码:
<img name="loadingImage" id="loadingImg" src="http://www.ppimusic.ie/images/loading_anim.gif " width="100px" height="100px" />
$('#loadingImg').hide();
$.ajax({
url: "test.html",
data: {data1:'smile'},
beforeSend:function() {
$('#loadingImg').show();
},
success:function(response) {
$('#loadingImg').hide();
//process the successful response
},
error:function(response) {
$('#loadingImg').hide();
//process the error response
}
});
快乐编码:)
关于javascript - 如何在加载 promise 对象时添加加载动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22069647/