我创建了一个名为ngMap的AngularJS模块,有两个用户要求我在需要时动态加载javascript http://maps.google.com/maps/api/js,这样用户就不必在需要时将此.js添加到他们的头部来在页面上显示地图。
出现的问题是如何动态加载此脚本,然后初始化.js依赖指令。
是否可以延迟指令的加载,直到加载了所需的.js?
发布于 2015-03-09 21:28:06
既然大家没有不同的答案,我想发表我自己的解决方案,尽管我不确定这是不是好的。
我已经将第三方.js依赖指令封装到一个名为lazy-load的指令中,其值为script source。
此指令只是通过删除并重新添加.js来延迟脚本的初始化,直到使用$timeout和$interval加载第三方html为止。
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
<div lazy-load="http://maps.google.com/maps/api/js">
<map center="Brampton" zoom="10">
<marker position="Brampton"></marker>
</map>
</div>https://stackoverflow.com/questions/28933333
复制相似问题