我们知道在应用的页面或者组件需要加载数据时,浏览器和angular渲染页面都需要消耗一定的时间。这里的间隔可能很小,甚至让人感觉不到区别;但也可能很长,这样会导致让我们的用户看到了没有被渲染过的页面。
这种情况被叫做Flash Of Unrendered Content (FOUC)(K)?and is always unwanted.下面我们将要介绍几个不同的方式防止这种情况发生在我们的用户身上。
1、ng-cloak
ng-cloak指令是angular的内置指令,它的作用是隐藏所有被它包含的元素:
<div ng-cloak> <h1>Hello {{ name }}</h1></div>
Ng-cloak实现原理为一个directive,页面初始化是在DOM的heade增加一行CSS代码,如下:
<pre class= “prettyprint linenums”> [ng/:cloak],[ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak{ Display:none ! important;}</pre><pre class= “prettyprint linenums”> [ng/:cloak],[ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak{ Display:none ! important; } </pre>
Angular将带有ng-cloak的元素设置为display:none.
在等到angular解析到带有ng-cloak节点的时候,会把元素上ng-cloak attribute和calss同时remove掉,这样就防止了节点的闪烁。如下:
<script type =”text/ng-template” id =”scenario.js-150”> It(‘should remove the template directive and css class',function(){ Expect(element(‘.doc-example-live #template1').attr(‘ng-cloak')) not().toBeDefined(); Expect(element(‘.doc-example-live #template2').attr(‘ng-cloak')).Not().toBeDefined();});</script><script type =”text/ng-template” id =”scenario.js-150”> It(‘should remove the template directive and css class',function(){ Expect(element(‘.doc-example-live #template1').attr(‘ng-cloak')) not().toBeDefined(); Expect(element(‘.doc-example-live #template2').attr(‘ng-cloak')). Not().toBeDefined(); }); </script>
2、ng-bind
ng-bind是angular里面另一个内置的用于操作绑定页面数据的指令。我们可以使用ng-bind代替{{ }}的形式绑定元素到页面上;
使用ng-bind替代{{ }}可以防止未被渲染的{{ }}就展示给用户了,使用ng-bind渲染的空元素替代{{ }}会显得友好很多。
上面的例子可以重写成下面那样,这样就可以防止页面出现{{ }}了
<div> <h1>Hello <span ng-bind="name"></span></h1></div>
3、resolve
当在不同的页面之间使用routes(路由)的时候,我们有另外的方式防止页面在数据被完全加载到route之前被渲染。
在route(路由)里使用resolve可以让我们在route(路由)被完全加载之前获取我们需要加载的数据。当数据被加载成功之后,路由就会改变而页面也会呈现给用户;数据没有被加载成功route就不会改变, the $routeChangeError event will get fired.【$routeChangeError事件就(不)会被激活?】
新闻热点
疑难解答
图片精选