我想避免显示初始
JavaScript渲染视图的延迟.我希望用户立即看到内容并让Angular从那里获取内容.当Angular ngRoute可能会发生眨眼时,我不想只是替换这个ng-view.一旦用户点击另一条路线,我只希望它替换它.
让我们假设这是基本路线’/’.这已经存在于我的HTML中,从服务器呈现.
<div ng-view> <h1>Welcome. I am the first view.</h1> <p>Please do not replace me until a user has triggered another route.</p> </div>
我知道一个常见的方法是在ng-view中有一些服务器端代码,当Angular加载时它只是替换它.这不是我想要做的.我希望Angular加载并理解这实际上已经是我的第一个视图了.
关于如何做到这一点的任何创意?我查看了源代码 – 没有运气.甚至可以让Angular只在不同的情况下替换HTML.
编辑:
我不打算在服务器端渲染模板以用作Angular模板.我希望在服务器端渲染我的整个index.html,这已经包含了用户需要查看的这个初始基本路由的所有内容.
解决方法
任何手机上6-10秒都很糟糕.我不会责怪角度在这里,角度只有30kb,如果仍然太慢,你选择了错误的框架来完成任务.
使用分析工具来了解正在发生的事情.
>您正在处理的应用程序有多大?
>您可以将应用程序拆分为子应用程序吗?
>你是否已经为CSS& JS?
>你是否懒得加载你的所有观点&控制器?
>你在压缩一切吗? (gzip的)
无论如何,可以在服务器端为index.html进行预处理
例如,您可以使用nodejs进行预处理,并缓存预处理的index.html.
你的nodejs预处理器可以做(伪代码):
function preprocessIndexHtml(queryString) { if(cached[queryString])) return cached[queryString]; // assume angular.js is loaded // routeConfiguration is an object that holds controller & url. var routeConfiguration = $routeProvider. figureOutRouteConfigurationFor(queryString); var domTree = $(file('index.html')); var $rootScope = $injector.get('$rootScope'); // find ng-view and clone it var yourNgView = $($("attribute[ng-view='']").outerHTML); // le's get rid of existing ng-view attribute // and configure new ng-view with templateUrl & controller. yourNgView.RemoveNgViewAttribute(); yourNgView.AddAttribute("ng-controller",routeConfiguration.controller); yourNgView.AddAttribute("ng-view",routeConfiguration.templateUrl); // compile the view & pass the rootScope. $compile(yourNgView)($rootScope); // replace the existing dom element with our compiled variant $("attribute[ng-view='']").replaceHtmlWith(yourNgView); // we can now cache the resulted html. return cached[queryString] = domTree.html; }