jQuery Mobile 1.1中如何在重型处理之前显示加载旋转器?

3

我正在尝试让一个“spinner”出现,但是我已经疯了。我已经将我的大量处理函数绑定到了一个按钮上:

$(document).delegate("#clearread", "tap", onClearRead);

所以当点击时,它会调用这个:

var onClearRead = function() {

setTimeout($.mobile.showPageLoadingMsg, 5);  

// Civilised cleaning of saved status
var jStorIndex = $.jStorage.index();
for (var i = 0; i < jStorIndex.length; i++) {
    if( jStorIndex[i] != "version" ) {
        $.jStorage.deleteKey(jStorIndex[i]);
    }
}   

// Load articles afresh
loadArticles();

$.mobile.changePage("#choosearticle");

} //onClearRead

我发现当文章被清除/加载时(大约10秒),旋转图标没有出现,但只在#choosearticle页面加载时(0.5秒)短暂出现一次。 我做错了什么? 我在应用程序的其他地方使旋转图标起作用。
谢谢

@Nirmal Patel 刚刚解决了我的问题,但是有没有人知道为什么需要一个疯狂的随机 settimeout?我已经读到这与 CPU 争用有关,有人能够详细解释一下吗? - Alveoli
1
问题在于JS在浏览器中只运行在单个线程中。因此,如果您进行了大量处理,浏览器在JS完成之前不会尝试重新绘制/重绘内容。而当JS完成时,我们已经调用了changePage()... setTimeout只是给浏览器足够的喘息时间来执行其他任务,然后再回到JS的重负工作。 - Nirmal Patel
终于有些清晰了 - 谢谢! - Alveoli
2个回答

4

试试这个:

$(document).delegate("#clearread", "tap", onClearRead);

var onClearRead = function() {
$.mobile.showPageLoadingMsg();
setTimeout(function(){  
        //Your heavy processing
        $.mobile.changePage("#choosearticle");
    }, 5);
} //onClearRead

1
是的,它有效 - 谢谢!我发现如果设备速度较慢,则可能需要增加毫秒数(例如100)。否则,旋转图标仍不会出现。 - Alveoli

0

jQuery.show( [duration ] [, complete ] )

将繁重的处理放在“complete”函数槽中,确保在显示发生之前,调用show方法的对象是可见的。

相关SO答案

https://dev59.com/iGAf5IYBdhLWcg3wbSQh#25207120

使用jQuery加载整个HTML页面并显示旋转图标

使用基于CSS的旋转图标的示例

CSS

@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg); }

  100% {
    -moz-transform: rotate(359deg); } }

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg); }

  100% {
    -webkit-transform: rotate(359deg); } }

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg); }

  100% {
    -o-transform: rotate(359deg); } }

@-ms-keyframes spin {
  0% {
    -ms-transform: rotate(0deg); }

  100% {
    -ms-transform: rotate(359deg); } }

@keyframes spin {
  0% {
    transform: rotate(0deg); }

  100% {
    transform: rotate(359deg); } }

.icon-spin {
  display: inline-block;
  -moz-animation: spin 2s infinite linear;
  -o-animation: spin 2s infinite linear;
  -webkit-animation: spin 2s infinite linear;
  animation: spin 2s infinite linear; }

使用 Font Awesome 的 HTML

<div id="spinner" data-bind="visible: isSpinning" style="padding: 10px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #cccccc; z-index: 1; filter: alpha(opacity=30);">

    <i class="fa fa-spinner fa-spin fa-5x"></i>
</div>

JavaScript

$('#spinner').show(100, function() {
  // Once the spinner is visible then run the heavy function.
  heavyProcessingFunction();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接