Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ngif not remove script tags from my code?

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>
like image 449
healthycola Avatar asked Feb 08 '16 07:02

healthycola


2 Answers

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.

like image 175
charlietfl Avatar answered Oct 11 '22 13:10

charlietfl


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;
    }
});
like image 1
Alexandre Annic Avatar answered Oct 11 '22 15:10

Alexandre Annic