javascript - How to dynamically add script tag in HEAD with AngularJS -
i trying dynamically add script tag in angular application. wrote function:
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); };
the script injected head tag, in console following error:
referenceerror: io not defined
how can correctly inject script in head ?
edit: if manually add script head dont error , application works correctly
resolved code script injection:
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; };
to inject script need call this:
loadscript('https://mysite.com/someplugin.js').then(function() { // script loaded succesfully. // can start using functions someplugin.js }).catch(function() { // there error loading script. meh });
Comments
Post a Comment