The requirement is to load the js
file related to the plug-in when calling a directive that encapsulates the third-party plug-in, so as to achieve on-demand loading, but without requireJS
.
My initial idea is to use directive
to dynamically load related link
files in the jquery
function of js
, but this way I don’t know when the file loading is completed.
The relevant code is as follows (taking packaging select2
as an example)
<p ng-app="app" ng-controller="FooController as vm">
<select my-select2 ng-model="vm.selector">
<option value="aaaa">aaaaa</option>
<option value="bbbb">bbbbb</option>
<option value="cccc">ccccc</option>
</select>
<p ng-bind="vm.selector"></p>
</p>
var app = angular.module('app', []);
app.controller('FooController', function() {
var vm = this;
});
//自定义指令,简单封装select2, 这里只是以select2为例
app.directive('mySelect2', function($timeout) {
return {
link: function(scope, ele, attr) {
//目前的想法是在这儿用jq动态加入script标签导入select2源文件
//但是文件是异步加载的,无法知道什么时候加载完
$('body').append('<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></sc'+'ript>');
//现在用timeout等select2加载好,模拟出应该实现的效果 **求各位给个正确的方案**
$timeout(function() {
$(ele).select2(); //主要为了元素可以调用这个方法,这是select2插件的初始化方法
}, 3000);
}
};
});
codepen link
angularJS
?
Well, the answer is ocLazyLoad. The following is part of the modified code.
ps: The principle is to use ajax to asynchronously request the target js file, and then put the requested text into the script tag in the callback function. Join the dom and then make plug-in related calls?
app.directive('mySelect2', function($timeout, $ocLazyLoad) {
return {
link: function(scope, ele, attr) {
ele.hide();
$ocLazyLoad.load(['https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css'])
.then(function() {
$(ele).select2();
});
}
};
});