naughty boy
naughty boy

Reputation: 2149

Unable to properly load external script without jquery

I am trying to lazy load a directive within another directive based on a condition. I have a main directive and within it I have a <script> tag. The included directive loads properly only when jquery is present, the problem is that not all of my pages load jquery. There is also a second warning...

synchronous XMLHttpRequest on the main thread is deprecated.

Which I should be able to suppress if I find a pure angularJs way of loading the script.

Here is my setup

<my-directive>
    <script ng-if="expression" src="../path" type="application/javascript"></script>
</my-directive>

very simple, but it only works if jquery is there to load it. I tried to load it via $http.get() request and then eval() (which I know the dangers) but that did not work.

Upvotes: 1

Views: 110

Answers (1)

scniro
scniro

Reputation: 16979

Here is a way which leverages the $http approach. You can create a directive which augments your <script> tag for this functionality, checking for a defined type attribute. You could of course modify this check however you'd like. Observe the following...

app.directive('script', function($http) {
    return {
        restrict: 'E',
        scope: false,
        link: function(scope, elem, attrs) {
            if (attrs.type === 'text/javascript-lazy') {
                $http.get(attrs.src).then(function(response) {
                    var code = response.data;
                    var f = new Function(code);
                    f();
                });
            }
        }
    };
});

<!-- retrieved -->
<script type="text/javascript-lazy" ng-if="true" src="script.js"></script>
<!-- not retrieved -->
<script type="text/javascript-lazy" ng-if="false" src="script.js"></script>

This will work inside an element wrapped directive as well.


Plunker - working demo

Upvotes: 1

Related Questions