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;
});
//自定義指令,簡(jiǎn)單封裝select2, 這里只是以select2為例
app.directive('mySelect2', function($timeout) {
return {
link: function(scope, ele, attr) {
//目前的想法是在這兒用jq動(dòng)態(tài)加入script標(biāo)簽導(dǎo)入select2源文件
//但是文件是異步加載的,無(wú)法知道什么時(shí)候加載完
$('body').append('<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></sc'+'ript>');
//現(xiàn)在用timeout等select2加載好,模擬出應(yīng)該實(shí)現(xiàn)的效果 **求各位給個(gè)正確的方案**
$timeout(function() {
$(ele).select2(); //主要為了元素可以調(diào)用這個(gè)方法,這是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();
});
}
};
});
歡迎選擇我的課程,讓我們一起見(jiàn)證您的進(jìn)步~~