首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为指令动态添加第三方.js依赖项

问为指令动态添加第三方.js依赖项
EN

Stack Overflow用户
提问于 2015-03-09 07:53:20
回答 1查看 419关注 0票数 1

我创建了一个名为ngMap的AngularJS模块,有两个用户要求我在需要时动态加载javascript http://maps.google.com/maps/api/js,这样用户就不必在需要时将此.js添加到他们的头部来在页面上显示地图。

出现的问题是如何动态加载此脚本,然后初始化.js依赖指令。

是否可以延迟指令的加载,直到加载了所需的.js?

EN

回答 1

Stack Overflow用户

发布于 2015-03-09 21:28:06

既然大家没有不同的答案,我想发表我自己的解决方案,尽管我不确定这是不是好的。

我已经将第三方.js依赖指令封装到一个名为lazy-load的指令中,其值为script source。

此指令只是通过删除并重新添加.js来延迟脚本的初始化,直到使用$timeout和$interval加载第三方html为止。

代码语言:javascript
复制
app.directive('lazyLoad', function($interval, $compile, $timeout) {
  var directiveDefinitionObject = {
    compile: function(tElement, tAttrs) {
      (!tAttrs.lazyLoad) && console.error("requires lazy-load");
      var savedHtml = tElement.html(), src = tAttrs.lazyLoad;
      if (document.querySelector("script[src='"+src+"']")) {
        return false;
      }

      tElement.html('');  // will compile again after script is loaded
      return {
        pre: function(scope, element, attrs) {
          var scriptEl = document.createElement("script");
          scriptEl.src = src;
          document.head.appendChild(scriptEl);

          var interval = $interval(function() {
            if (document.querySelector("script[src='"+src+"']")) {
              console.log('script  loaded, ' + src);
              $timeout(function() {  // give some time to execute the script
                element.html(savedHtml);
                $compile(element.contents())(scope);
                $interval.cancel(interval);               
              }, 100);
            }
          }, 100, 10);
        }
      };
    }
  };
  return directiveDefinitionObject;
});

这部分是html

代码语言:javascript
复制
<div lazy-load="http://maps.google.com/maps/api/js">
  <map center="Brampton" zoom="10">
    <marker position="Brampton"></marker>
  </map>
</div>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28933333

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档