godblessstrawberry
godblessstrawberry

Reputation: 5058

Remove html node created with javascript

I want to preload css background images via creating fake ones that will hold src until the actual image is cached.

How do I remove preloaderImg elements that was created before? Do I need to remove them to prevent memory leaks or browser will handle this?

let preloaderImg = document.createElement("img");
preloaderImg.src = this.finalSrc;
let subscription = fromEvent(preloaderImg, 'load').subscribe((event: Event) => {
    this.removeClass("loading");
    this.addClass("loaded");
    this.setBackgroundImage(this.finalSrc);
    subscription.unsubscribe();
});

Upvotes: 0

Views: 50

Answers (1)

Randy Casburn
Randy Casburn

Reputation: 14165

You can set preloaderImg to null after you unsubscribe. That will set it up for garbage collection in the future.

What you've read is that as long as there is any reference to an object, it will be held in memory. This is the nature of closures and how they work. As soon as all references to the object are removed, then the object will be garbage collected (eventually). Since this is the only place you reference that variable, you are assured that it will be garbage collected after you set it to null (on each iteration).

Upvotes: 1

Related Questions