2
votes

I am trying to lazy load the external script (in my case ckeditor) in a directive only when its needed.

HTML Template - directives/myEditor.tmplt

<div>
   <textarea name="editor1" id="editor1" rows="10" cols="80">

       This is my textarea to be replaced with CKEditor.

   </textarea>
</div>

Angular Module - MyEditorModule

define(['angular'], function(angular){

   var moduleName = 'MyEditorModule';

   angular
          .module(moduleName)
          .directive('myEditor',function($scope){
             return {
                 restrict: 'E',
                 templateUrl: 'directives/myEditor.tmplt',
                 link: function(scope, element){

                     scope.CKEDIOTR_LOADED = false;

                     require([
                        'https://cdn.ckeditor.com/4.4.7/standard/ckeditor'
                     ], function(){

                          scope.CKEDIOTR_LOADED = true;
                          CKEDITOR.replace('editor1');

                          /**
                           *  Registering other actions for CKEDITOR     
                           *
                           **/

                     });
                 }
             };
          });

   return moduleName;
});

I have some doubts

  1. is it safe to load scripts like this inside controller or link function ?
  2. do i have to trigger $apply or $digest inside CKEditor's require callback function ?
  3. is there any better and cleaner way of doing this kind of lazy loading ?
1
I don't think your method of lazy loading is wise. Your views are not going to be the bulk of your application code anyway (or they shouldn't be) - large views can be broken up using ng-repeat and the like. I think this might be premature optimization frankly. What is leading you to decide to do this? In any case, Angular does not have support for per-directive lazy loading. - Dan
Checkout angular-require-lazy for potentially useful ideas; it does lazy loading in Angular with RequireJs. If you run the example, go to the "Expenses" menu and open the graph, it is a similar case to the one you need. - Nikos Paraskevopoulos
@DanPantry i have multi-pages in the single page application and i don't want to load the ckeditor in all the pages. it should only get loaded when its needed - jad-panda

1 Answers

0
votes

For third party resources, it's usually best to include this is as script in your page on the bottom of the body. Looks like ckeditor has actually created a bower package, so I would recommend just using the bower package as it will be strapped in the same way: http://docs.ckeditor.com/#!/guide/dev_package_managers.

This way, you do not have to $digest or wait for the ckeditor script to load. Is there a reason you only want to load it on this page? There are ways to insert the script element on the page, but it's best to stay away from that type of DOM manipulation with Angular.