在启动脚本之前显示loading.gif

时间:2011-12-13 19:26:21

标签: javascript jquery html

我使用的脚本需要一些时间来加载,所以我想在用户等待时显示loading.gif图像。当我抬头看看如何做到这一点时,我想出了类似的东西:

    <div>
        <div class="loader" style="position:center;top:300px;background-color:white;padding:20px;margin-left:45%;">
                <img src="visualisation-arbor/loading36.gif" alt="Loading Image"/>
        </div>
        <canvas class="explore_area" id="viewport">
        </canvas>   
    </div>

<script type="text/javascript"> 
    jQuery(function($){jOWL_loader.load()});
    function loop(){
        var loaded = jOWL_loader.get();
        if (!loaded){
            setTimeout(function(){loop()}, 5)
        } else {
            $('.loader').hide();
            visualize(loaded)
        }
    }
    loop();
</script>

使用此代码,没有显示gif图像。我是否实施了错误或错误的订单?

btw:.gif文件存储在本地,大小为4 kb

2 个答案:

答案 0 :(得分:1)

我通常只做这样的事情:

$('#divWhereContentIsLoaded').hide().html('<img src="loading.gif" />').fadeIn().load('thingToLoad.php', {}, function(){
    //something to do after it is loaded?
});

希望这会有所帮助;)

答案 1 :(得分:0)

的CSS

.loading {position:center;
top:300px;
background-color:white;
padding:20px;
margin-left:45%;
background-image:url('visualisation-arbor/loading36.gif')}

的HTML

<div>
        <div class="loading" >
        </div>
        <canvas class="explore_area" id="viewport">
        </canvas>   
    </div>

javascript,加载函数是异步的

    //requires jquery > 1.5
        $(document).ready(function(){
    // wrap the Asynchronous load call in a deferred object
           var wrapperFunction = function wrapLoader(deferred){
           jOWL_loader.load();
    //flags the load as done.
           deferred.resolve();
    //return the promise object, so we can chain events off this entirely asynchronous function
           return deferred.promise();
        };
    //create a deferred object, asynchronous
    //passes the newly created Deferred object as the first param to the function wrapLoader
          var ourDeferred = $.Deferred(wrapperFunction);
    // when the promise object's listener registers the 'deferred.resolve()' call, execute our done function.
           $.when(ourDeferred ).done(function(){
      $('div.loading').toggleClass("loading");
      }).done( function(){
  var loaded = jOWL_loader.get();
  visualize(loaded);
});

        });