javascript - AngularJS - 延迟加载 View

标签 javascript html angularjs

我正在创建一个单页主页站点,并希望通过延迟加载低于当前可见内容的 View 来减少初始页面加载时间并节省用户带宽。主页会相当长,有一个导航、标题、几个内容部分和一个页脚。我的目标是最初加载一个带有导航和粘性页脚的静态布局容器以及“根” Angular 应用程序。滚动或单击导航链接将导致加载下一个可见 View (单击跳转到多个 View 的导航链接应该加载用户将跳过的所有 View )。我知道这个任务有一个 jQuery 库,但我想坚持使用 Angular。

有没有一种简单的方法可以在 Angular 中以这种方式有条件地加载 View ?

最佳答案

这是我想出的,只是一个简单的例子。您可以通过多种方式完成此操作。如果您想要更精细的调整,您甚至可以编写自己的指令而不是使用 ng-include/ng-repeat

Live demo here 嗯,plnkr 现在有一些问题。如果页面甚至会加载,有时似乎无法找到模板(请参阅控制台日志..它正在尝试加载它们,因此代码工作正常)。 Here's a jsbin demo also ,但模板不会加载任何内容(空)。

<div ng-repeat="lazy in loaded">
  {{lazy}}
  <div ng-include="lazy"></div>
</div>
<button ng-click="loadNext()">Load Next</button>
<button ng-click="unload()">Reset</button>



var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  var toLoad = [ //list the templates to be loaded
    'tmpl.html',
    'tmpl2.html',
    'tmpl3.html'
  ];
  $scope.loaded = []; //anything in here will be loaded to the page
  $scope.loadNext = function() {
    if (toLoad.length) { //if there are any item left to load
      $scope.loaded.push(toLoad.splice(0, 1)[0]); //move first item to "loaded"
    }
  };
  $scope.unload = function() {
    toLoad = $scope.loaded.splice(0, $scope.loaded.length); //move all items back to "toLoad"
  };
});

关于javascript - AngularJS - 延迟加载 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18663874/

相关文章:

javascript - 如何在 d3.js 元素上使用 intro.js

javascript - 如何让 CSS 影响解释 CSS 后生成的 DOM 元素?

php - 将 PHP 页面转换为静态 HTML 页面的最简单方法

javascript - <td> focusin 事件.addclass

javascript - AngularJS ng-repeat 不适用于 Promise.all

javascript - 在 Angular 中的 dom 元素上使用两次 ng-controller

javascript - Windows Phone 上的初始 window.orientation 始终为 0

javascript - 将 Angular 6 中对象的字符串名称更改为自定义名称

javascript - 将函数作为 AngularJS 中的选择值传递

angularjs - 用于 Angular E2E测试的 Protractor : What is the best approach to manage test data?