获取网站的进度 - 加载脚本&图书馆

时间:2016-05-22 09:26:25

标签: javascript angularjs angular client

我在我的网站上使用了很多脚本和库,需要5到8秒才能加载。 离。

<script type="text/javascript" src="../lib_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="../lib_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../lib_components/angular/angular.js"></script>
<script type="text/javascript" src="../lib_components/angular-resource/angular-resource.min.js"></script>
<script type="text/javascript" src="../lib_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<script type="text/javascript" src="../lib_components/angular-cookies/angular-cookies.min.js"></script>
<script type="text/javascript" src="../lib_components/angular-ui-router/release/angular-ui-router.min.js"></script>
<script type="text/javascript" src="../lib_components/lodash/dist/lodash.min.js"></script>
<script type="text/javascript" src="../scripts/js/overdo.js"></script>

    

我想显示一个加载栏,直到所有脚本都已加载,任何人都可以指导我什么需要为此完成?

1 个答案:

答案 0 :(得分:1)

当您要加载的所有脚本同步加载(您不使用模块加载程序,异步属性等)时,可以使用非常简单的方法 - 就像您的示例中一样。

诀窍是在所有繁重的脚本之前,在页面上添加进度指示器脚本 first first 。内联这个脚本也是有意义的(因为理想情况下它不应该太大):

<script>
// some progress bar implementation progress.show()
console.log('showing progress, loading bar, etc.');
</script>

<script src="../lib_components/jquery/dist/jquery.min.js"></script>
<script src="../lib_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../lib_components/angular/angular.js"></script>
<script src="../lib_components/angular-resource/angular-resource.min.js"></script>
<script src="../lib_components/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
<script src="../lib_components/angular-cookies/angular-cookies.min.js"></script>
<script src="../lib_components/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="../lib_components/lodash/dist/lodash.min.js"></script>
<script src="../scripts/js/overdo.js"></script> 

<script>
// hiding loading bar
console.log('scripts loaded')
</script>

现在,为了实现实际进度条,它取决于您如何呈现以及呈现什么。但是,请记住,根据您放置这些脚本的位置,DOM树可能尚未加载(如果脚本位于<head>中)。无论如何,我建议在关闭</body>之前放置脚本。这种方法的理想结构是:

<!DOCTYPE html>
<html>
<head>
  <!-- some styles, no scripts here -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
  <link rel="stylesheet" href="assets/styles.css" />
</head>
<body>

  <div class="loading" hidden>Loading...</div>

  <!-- Some application HTML code -->

  <script>
    // show/create progress/loading
    var loading = document.querySelector('.loading')
    loading.hidden = false
  </script>

  <!-- many script tags ... -->
  <!-- ... -->

  <script>
    // hide/remove progress/loading
    loading.parentNode.removeChild(loading)
  </script>

</body>
</html>