Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-if directive briefly renders even when condition is false before removing element

In the below template, I would expect the script tag to never render, and the alert script to never execute. However it does.

<div ng-if="false">
    <script>alert('should not run')</script>
    Should not appear
</div>

This is causing us huge performance problems on mobile devices as we wrap large DOM and directive structures in ng-ifs with the expectation they will not render when the condition is false.

I have also tested ng-switch which behaves in the same manner.

Is this expected behaviour? Is there a way to avoid the unnecessary render?

JSFiddle

like image 592
WearyMonkey Avatar asked Mar 18 '15 11:03

WearyMonkey


1 Answers

It may seem backward, but ngIf deals more with the removal of DOM, rather than the addition. Before the controller finishes instantiating, the DOM still exists. This is generally a good thing, and allows you to have graceful degradation for users without JS (or, alternatively, an initial loading state).

If you don't want the inner DOM to render, place it in a directive (either its own directive, or via ng-include) or in a view.

Example 1 (understanding why the script runs):

To help yourself understand the flow a bit better, you can update the example to instead be:

<div ng-if="false">
    {{"Should not appear"}}
    <script>alert('should not run')</script>
</div>    

https://jsfiddle.net/hLw0nady/6/embedded/result/

You will notice that when the alert pops up, Angular has not yet interpolated "Should not appear" (it appears in its braces). After you dismiss the alert, however, it disappears.

Example 2 (how to prevent the alert):

An example of hiding the code that "should not run" in a directive can be viewed here: https://jsfiddle.net/hLw0nady/4/

In this example, only if you replace ng-if="false" with ng-if="true" will you get your alert.

like image 123
DRobinson Avatar answered Oct 05 '22 20:10

DRobinson