Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
LazyLoad directive for loading external javascript for AngularJs. In this example, I use google maps' API as the external library being loaded
angular.module('testApp', []).
directive('lazyLoad', ['$window', '$q', function ($window, $q) {
function load_script() {
var s = document.createElement('script'); // use global document since Angular's $document is weak
s.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize';
document.body.appendChild(s);
}
function lazyLoadApi(key) {
var deferred = $q.defer();
$window.initialize = function () {
deferred.resolve();
};
// thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
if ($window.attachEvent) {
$window.attachEvent('onload', load_script);
} else {
$window.addEventListener('load', load_script, false);
}
return deferred.promise;
}
return {
restrict: 'E',
link: function (scope, element, attrs) { // function content is optional
// in this example, it shows how and when the promises are resolved
if ($window.google && $window.google.maps) {
console.log('gmaps already loaded');
} else {
lazyLoadApi().then(function () {
console.log('promise resolved');
if ($window.google && $window.google.maps) {
console.log('gmaps loaded');
} else {
console.log('gmaps not loaded');
}
}, function () {
console.log('promise rejected');
});
}
}
};
}]);
@bandicoot86
Copy link

bandicoot86 commented Jun 26, 2014

Nicely done! Thanks!

Copy link

ghost commented Jun 26, 2015

Thanks for posting this, very intuitive, but how would you use an API key, in this instance?

@velvok
Copy link

velvok commented Jan 29, 2016

Good job!
Couple things to think about though:

  • I would also remove load event listener once its not needed anymore:
$window.addEventListener('load', function onloadFunc () { 
    $window.removeEventListener('load', onloadFunc, false);
    load_script();
}, false);
  • The event listener is not always helpful since document can be already in the "ready" state at the moment you attach the listener. Bacisally you need to check if document is already ready first and if not then attach listener. Otherwise just call load_script function.

@raduolivas
Copy link

raduolivas commented Nov 3, 2016

Sorry, i dont know if i get it but in my code function load_script() is never been reach!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment