Search code examples
javascriptjqueryangularjsjqlite

What is the Angular jqlite equivalent or solution for $( new Image() )?


I have created a factory to pre-load images. Somewhere in this factory I use:

var image = $( new Image() )
                    .load(
                        function( event ) {
                            // Do Stuff
                        }
                    )
                    .error(
                        function( event ) {
                            // Do Stuff
                            );
                        }
                    )

This code was working. But I am working on removing the jQuery lib from my project and rely solely on using Angular's build-in jqlite.

I tried to find the solution by myself, but i just can't figure it out. I need the .load and .error function events to properly catch pre-load states. This is a factory, so I do not want to create DOM elements here.

Does anyone has an elegant solution for this?


Solution

  • Yes, you don't need jQuery here at all. Equivalent code in vanila JS would be:

    var image = new Image();
    
    image.onload = function (event) {
        // Do Stuff
    };
    
    image.onerror = function (event) {
        // Do Stuff
    };
    
    image.src = src;