Detect when images are loaded

Hi ionic community,

I have been spending many hours trying to figure out how to detect when images are loaded. So far I found a few possible solutions: (but they don’t seem to work for me, Did I do something wrong?)

  1. Using native javascript window.onload = doSomething();. Works on browser but doesn’t work on iOS.

  2. Using $scope.$on(’$ionicView.loaded’, function(){ doSomething}); But it triggers before images are loaded. Kind of like how document.onload works.

  3. I tried using img src="" onload="doSomething() but it throws errors like “Uncaught ReferenceError: doSomething is not defined”. Doesn’t matter if I define doSomething() in the $scope or as a native javascript function.

  4. ng-cloak also doesn’t work for this

I am trying to figure this out because my page loads before my images do and I don’t want users to see the page without the images. I use $ and I intend to use $ionicLoading.hide() when all the images are loaded. Is there any other way to achieve something of similar effect?

Use a directive. Check this answer. Then, apply your own logic to handle when all images are loaded.

app.directive('imageonload', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function() {
                alert('image is loaded');
1 Like

Thanks so much for the reply!

It works! Silly me… I saw this solution before but didn’t explore it because I wanted something that can detect if ALL the images are loaded. Anyway, it works fine, though I think it is because usually when one image loads the rest are more or less loaded as well.

I would create a directive on the container, get how many images are and then count when each image is loaded (or not) and compare.

Sounds good! Shall post here when I get it done. Thanks a bunch!