我希望避免显示初始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
,这已经包含了用户需要查看的这个初始基本路由的所有内容。
答案 0 :(得分:-1)
使用分析工具来了解正在发生的事情。
无论如何,可以在服务器端为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;
}
答案 1 :(得分:-2)
ngCloak
ngCloak指令用于防止浏览器在加载应用程序时以原始(未编译)形式短暂显示Angular html模板。使用此指令可避免由html模板显示引起的不良闪烁效应。
https://docs.angularjs.org/api/ng/directive/ngCloak
<body ng-cloak>
您应该阅读这篇文章http://sc5.io/posts/how-to-implement-loaders-for-an-angularjs-app