Filippo oretti
Filippo oretti

Reputation: 49873

Angular js - require js file from view using lazy load

How can i include multiple js files in lazy load, so when page finished to load and angular has been executed?

I tryed with a custom directive and the code looks like: //html

<ng-lazy-load data-type="script" data-src='["file.js"]'></ng-lazy-load>

//directive

.directive('ngLazyLoad', [function () {
    return {
      restrict: 'E',
      templateUrl:'views/modules/module_lazy_load.html',
      scope:true,
      link: function ($scope, element, attr) {
        if(attr.type === 'script'){
          $scope.src = JSON.parse(attr.src);
        }

      }
    };
  }]);

//directive view

<script ng-if="src" ng-repeat="path in src" src="{{path}}"></script>

//file.js to be included in lazy load

alert('daf***');

Upvotes: 0

Views: 395

Answers (2)

Kos
Kos

Reputation: 72319

Nay. It's a temporally inconsistent idea: A script tag is executed when it's encountered while parsing the DOM. What would it even mean to "switch it off" later? It will have already been executed by then.

Upvotes: 0

Sten Muchow
Sten Muchow

Reputation: 6711

I dont think so, as script is loaded before angular can take over.

How about a directive that can check your stuff and then you can $document.write the script to the index.html?

Have the controller in charge of the scope variable be injected into the directive, then it can write to the html conditionally.

Upvotes: 1

Related Questions