Why does ngif not remove script tags from my code?
Asked Answered
B

2

6

I have a few script tags I want removed on a condition. In the DOM I see that they are not there (they're commented out), but i still see console spew from them. Are the script tags loaded regardless? If so, does anyone have any workaround for this?

<script ng-if="myCondition" src="blah blah.js"></script>
Bumgardner answered 8/2, 2016 at 7:26 Comment(0)
I
7

It wouldn't matter if they were removed or not. By the time angular bootstraps and starts DOM manipulation all script tags will have been compiled by browser.

Removing a script tag does not remove the code that has already been compiled.

Without a lot more information on what it is you are trying to accomplish , or what the scripts do, this is about all that can be offered for now.

I would suggest you read up on the basics of how a web page gets processed by the browser as the html gets compiled to the DOM. The instant it encounters a script tag with an src , a request is made for that file and there is no way to intercept it.

Intrench answered 8/2, 2016 at 7:32 Comment(1)
thanks! i was trying to retain common code (one page had script tags and one didn't), and i guess my fundamentals were out of order. this helped a lot!Bumgardner
C
1

As a workaround you could insert script manually as follow:

function loadScript() {
    var $script = document.createElement('script');
    $script.src = 'blah blah.js';
    $script.id = 'someId';
    document.body.appendChild($script);
}

$rootScope.watch(myCondition, function(value) {
    if(myCondition && !document.getElementById('someId') {
        loadScript();
        isScriptInserted = true;
    }
});
Castiglione answered 18/1, 2018 at 13:39 Comment(1)
use $rootScope.$watch instead of $rootScope.watchCountermark

© 2022 - 2024 — McMap. All rights reserved.