Created
April 17, 2017 04:26
-
-
Save envil/74b23a495d4a064bad5bddcde1fa510b to your computer and use it in GitHub Desktop.
Factory to inject non-Angular library to the application, here is Lodash for example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
angular | |
.module('shared.factories') | |
.factory('_', LodashFactory); | |
LodashFactory.$inject = ['$window', '$state']; | |
function LodashFactory($window, $state) { | |
if(!$window._){ | |
var lodashCdnUrl = 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js'; | |
loadScript(lodashCdnUrl, function () { | |
return $window._; | |
}, function () { | |
$state.to('error', {code: 424}); | |
}); | |
} | |
return $window._; | |
} | |
function loadScript(url, successCallback, errorCallback) { | |
var script = document.createElement("script"); | |
script.type = "text/javascript"; | |
lodashScript.async = false; | |
if (script.readyState) { //IE | |
script.onreadystatechange = function () { | |
if (script.readyState == "loaded" || script.readyState == "complete") { | |
script.onreadystatechange = null; | |
successCallback(); | |
} else { | |
errorCallback(); | |
} | |
}; | |
} else { //Others | |
script.onload = successCallback; | |
script.onerror = errorCallback; | |
} | |
script.src = url; | |
(document.getElementsByTagName('head')[0] | |
|| document.getElementsByTagName('body')[0]).appendChild(script); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment