Skip to content

Instantly share code, notes, and snippets.

Created October 31, 2013 19:40
  • Star 21 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
Star You must be signed in to star a gist
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 = '';
function lazyLoadApi(key) {
var deferred = $q.defer();
$window.initialize = function () {
// thanks to Emil Stenström:
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 ($ && $ {
console.log('gmaps already loaded');
} else {
lazyLoadApi().then(function () {
console.log('promise resolved');
if ($ && $ {
console.log('gmaps loaded');
} else {
console.log('gmaps not loaded');
}, function () {
console.log('promise rejected');
Copy link

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?

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);
}, 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.

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