Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

javascript - Best way to preload images with Angular.js

Angular's ng-src keeps previous model until it preloads image internally. I am using different image for the banner on each page, when I switch routes, i change main view, leaving header view as it is, just changing bannerUrl model when I have it.

This is resulting in seeing previous banner image while new one is loading.

I was surprised that there's no directive for it yet, but I wanted to make a discussion before trying to build one.

What I want to do I think is have banner model on custom attribute. like:

<img preload-src="{{bannerUrl}}" ng-src="{{preloadedUrl}}">

Then $scope.watch for bannerUrl change, and as soon as it changes, replace ng-src with loader spinner first, and then create temproary img dom element, preload image from preload-src and then assing it to preloadUrl.

Need to think how to handle multiple images too for galleries for example.

Does anyone have any input on it? or maybe someone can point me to existing code?

I've seen existing code on github that uses background-image - but that doesn't work for me as I need dynamic height/width as my app is responsive, and I cannot do it with background-image.

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Having the 2 urls on the directive seems a touch overcomplicated. What I think is better is to write a directive that works like:

<img ng-src="{{bannerUrl}}" spinner-on-load />

And the directive can watch ng-src and (for example) set visibility:false with a spinner until the image has loaded. So something like:

scope: {
  ngSrc: '='
},
link: function(scope, element) {
  element.on('load', function() {
    // Set visibility: true + remove spinner overlay
  });
  scope.$watch('ngSrc', function() {
    // Set visibility: false + inject temporary spinner overlay
  });
}

This way the element behaves very much like a standard img with an ng-src attribute, just with a bit of extra behaviour bolted on.

http://jsfiddle.net/2CsfZ/47/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...