Last active
September 3, 2016 23:28
-
-
Save santaklouse/947007eb1bc27cc1cc7aef888c22a4f4 to your computer and use it in GitHub Desktop.
Angular 1.* ; Preloads images in background by using valid css (when in $rootScope 'imgLoading' event emitted and value is false)
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
//using Lodash (https://lodash.com/) | |
.directive('imagesPreloader', ['$rootScope', function($rootScope) { | |
return { | |
restrict: 'A', | |
link: function($scope) { | |
var willBePreloaded, | |
preloadedHashes = {}, | |
imagesUrls = []; | |
var findInPreloaded = function(obj) { | |
return preloadedHashes[obj.id] && preloadedHashes[obj.id] === obj.src; | |
}; | |
var isShouldBePreloaded = function(obj) { | |
return obj && obj.src && !findInPreloaded(obj); | |
}; | |
$scope.background = ''; | |
willBePreloaded = function(objects) { | |
var values = _.chain(obj) | |
.map(function(snapshot){ | |
if (isShouldBePreloaded(obj)) { | |
imagePreload.addPreloaded(obj); | |
return 'url('+obj.src+') no-repeat -9999px -9999px'; | |
} | |
}) | |
.compact() | |
.value(); | |
if (!values.length) { | |
return; | |
} | |
$scope.background = ['background', imagesUrls.join(',')].join(': ') + ';'; | |
}; | |
var imagesToPreload = [ | |
{ | |
id:1, | |
src: 'https://www.google.com.ua/images/branding/googlelogo/1x/googlelogo_white_background_color_272x92dp.png', | |
{ | |
id:2, | |
src: 'https://www.google.com.ua/images/nav_logo229.png' | |
} | |
]; | |
$rootScope.$watch('imgLoading', function(value) { | |
if (_.isUndefined(value) || value) { | |
return; | |
} | |
willBePreloaded(imagesToPreload); | |
}); | |
} | |
} | |
}]) |
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
#o-preload-images { | |
display: none; | |
visibility: hidden; | |
position: absolute; | |
left: -999em; | |
} |
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
<div images-preloader id="o-preload-images" style="{{'{{background}}'}}"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment