我正在尝试在我的角度应用程序中动态添加脚本标记。为此写了一个函数:
var injectSocketIOLib = function (serverAddress) {
var wf = document.createElement('script');
wf.src = serverAddress + '/socket.io/socket.io.js';
wf.type = 'text/javascript';
wf.async = 'false';
document.head.appendChild(wf);
};
脚本被注入head标签,但在控制台中我收到以下错误:
ReferenceError: io is not defined
如何正确地将脚本注入头部?
编辑:如果我手动将脚本添加到头部,那么我不会收到此错误并且应用程序正常工作
解决了脚本注入的代码:
loadScript = function (src) {
var deferred = $q.defer();
var script = $document[0].createElement('script');
script.onload = script.onreadystatechange = function (e) {
$timeout(function () {
deferred.resolve(e);
});
};
script.onerror = function (e) {
$timeout(function () {
deferred.reject(e);
});
};
script.src = src;
$document[0].body.appendChild(script);
return deferred.promise;
};
注入脚本需要调用它:
loadScript('https://mysite.com/someplugin.js').then(function() {
// Script loaded succesfully.
// We can now start using the functions from someplugin.js
}).catch(function() {
// There was some error loading the script. Meh
});