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>
healthycola
  • 347
  • 4
  • 9

2 Answers2

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.

charlietfl
  • 164,229
  • 13
  • 110
  • 143
  • 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! – healthycola Feb 08 '16 at 08:12
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;
    }
});
Alexandre Annic
  • 7,089
  • 3
  • 28
  • 40