Skip to content

Instantly share code, notes, and snippets.

@neilsoult
Created October 31, 2013 19:40
Show Gist options
  • Save neilsoult/7255583 to your computer and use it in GitHub Desktop.
Save neilsoult/7255583 to your computer and use it in GitHub Desktop.
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');
});
}
}
};
}]);
Copy link

ghost commented Jun 26, 2015

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

@dmi3lab
Copy link

dmi3lab 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

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