As I load multiple images for different breakpoints (desktop, tablet, mobile) and cycle through them using `ng-repeat`, the unnecessary loading of all three image elements at once has become an issue:
<img ng-repeat="img in module.imgs" src="{{img.src}}" class="image-{{img.type}}" style="top: {{img.pos}}px">
This indiscriminate loading is evident in the network requests:
desktop.png GET 304 png angular.js:3151 243 B 4 ms
tablet.png GET 304 png angular.js:3151 243 B 5 ms
mobile.png GET 304 png angular.js:3151 243 B 3 ms
In an attempt to optimize this process, I decided to only load the image corresponding to the current breakpoint:
<img src="{{image.src}}" class="image-{{image.type}}" style="top: {{image.pos}}px">
$scope.$watch($scope.getWindowDimensions, function (newValue, oldValue) {
$scope.windowHeight = newValue.h;
$scope.windowWidth = newValue.w;
$scope.image = null;
if ($scope.windowWidth >= breakPoints['desk']) {
$scope.image = $scope.module.imgs[0];
} else if ($scope.windowWidth >= breakPoints['mid']) {
$scope.image = $scope.module.imgs[1];
} else {
$scope.image = $scope.module.imgs[2];
}
}, true);
However, every time the breakpoint changes, a new request is made even though the images have already been loaded:
desktop.png GET 304 png angular.js:3151 243 B 4 ms
tablet.png GET 304 png angular.js:3151 243 B 5 ms
mobile.png GET 304 png angular.js:3151 243 B 3 ms
tablet.png GET 304 png angular.js:3151 243 B 4 ms
mobile.png GET 304 png angular.js:3151 243 B 5 ms
I'm looking for a way to cache or store these images so they are loaded only when needed.
Here is the data structure of the controller:
$scope.module = {
imgs: [
{
type: 'desktop',
src: 'img/desktop.png',
pos: 0
},
{
type: 'tablet',
src: 'img/tablet.png',
pos: 0
},
{
type: 'mobile',
src: 'img/mobile.png',
pos: 0
}
]
};