admin管理员组

文章数量:1134247

I'm working on a realtime media browsing/playback application that uses <video> objects in the browser for playback, when available.

I'm using a mix of straight javascript, and jQuery,

My concern is specifically with memory. The application never reloads in the window, and the user can watch many videos, so memory management becomes a large concern over time. In testing today, I see the memory profile jumping by the size of the video to be streamed with each subsequent load, and never dropping back down to the baseline.

I've tried the following things with the same result:

1 - Empty the parent container containing the created element, eg:

$(container_selector).empty();

2 - Pause and remove children matching 'video', and then empty the parent container:

$(container_selector).children().filter("video").each(function(){
    this.pause();
    $(this).remove();
});
$(container_selector).empty();

Has anyone else run into this issue, and is there a better way to do this?

I'm working on a realtime media browsing/playback application that uses <video> objects in the browser for playback, when available.

I'm using a mix of straight javascript, and jQuery,

My concern is specifically with memory. The application never reloads in the window, and the user can watch many videos, so memory management becomes a large concern over time. In testing today, I see the memory profile jumping by the size of the video to be streamed with each subsequent load, and never dropping back down to the baseline.

I've tried the following things with the same result:

1 - Empty the parent container containing the created element, eg:

$(container_selector).empty();

2 - Pause and remove children matching 'video', and then empty the parent container:

$(container_selector).children().filter("video").each(function(){
    this.pause();
    $(this).remove();
});
$(container_selector).empty();

Has anyone else run into this issue, and is there a better way to do this?

Share Improve this question asked Jul 15, 2010 at 18:17 sparkey0sparkey0 1,6901 gold badge12 silver badges15 bronze badges 1
  • 3 I am updating the answer as things have evolved since this question was asked! I believe the 'delete' fix was almost certainly a browser bug at that time, and these days, i'd recommend pausing the video element, removing the src attribute and triggering reload. After that it can be safely removed from the DOM. – sparkey0 Commented Aug 1, 2018 at 19:48
Add a comment  | 

19 Answers 19

Reset to default 179 +100

It is very tricky to dispose video from the DOM structure. It may lead to browser crashing. Here is the solution that helped me in my project.

var videoElement = document.getElementById('id_of_the_video_element_here');
videoElement.pause();
videoElement.removeAttribute('src'); // empty source
videoElement.load();

this will reset everything, silent without errors !

Edit: Here are the full details as recommended in the Standard: https://html.spec.whatwg.org/multipage/media.html#best-practices-for-authors-using-media-elements

Hope it resolve your query.

This "solution" is reported to work, presumably because it would make those video container objects available for garbage collection (see the note below for a discussion of why delete shouldn't be making a difference). In any case, your results are likely to vary by browser:

$(container_selector).children().filter("video").each(function(){
    this.pause(); // can't hurt
    delete this; // @sparkey reports that this did the trick (even though it makes no sense!)
    $(this).remove(); // this is probably what actually does the trick
});
$(container_selector).empty();

Note: There's no doubt that the delete keyword is specified only to remove properties from objects (as others have pointed out in the comments). Logging this to the console both before and after the delete this line, above, shows the same result each time. delete this should do nothing and make no difference. Yet this answer continues to receive a trickle of votes, and people have reported that omitting delete this makes it stop working. Perhaps there's strangeness in how some browser JS engines implement delete, or an unusual interaction between a browser's delete and what jQuery is doing with this.

So, just be aware, if this answer solves your problem, that if it does work, it's not clear why that's the case, and it's just as likely to stop working for any number of reasons.

To reset the video to Blank without removing it

$("#video-intro").first().attr('src','')

It stops the video

delete(this); 

is not a solution. If it worked for x or y it is a browser misbehaviour. Read here:

The delete operator removes a property from an object.

The truth is that some browsers (Firefox for example) will cache in memory the video buffer when autoplay property is on. It is a pain to deal with.

Removing the video tag from the DOM or pausing it can only produce unstable results. You have to unload the buffer.

var video = document.getElementById('video-id');
video.src = "";

My experiment shows that it is done as so but unfortunately this is browser implementation not completely specified by the spec. You do not need to call load() after src change. When changing the src of a video tag you implicitly call a load() on it, this is stated in the W3C spec.

This snippet doesn't do any effecient DOM manipulations (no tag removal) and doesn't fire error event for <video> unlike this answer:

var video = document.getElementById('video');
video.removeAttribute('src');
video.load();

Furthermore, it doesn't fire loadstart event. And it's like it should work - no video, no load start.

Checked in Chrome 54 / FF 49.

Just to clarify for anyone trying this later, the solution was this: (confirmed with h264 videos in Safari 5.0, untested in FF/opera yet)

$(container_selector).children().filter("video").each(function(){
    this.pause();
    delete(this);
    $(this).remove();
});
$(container_selector).empty();

I was having an issue while dynamically loading some videos. I had two sources in my <video> element. One mp4 and the other webm as fallback. So I had to iterate through the <source>'s like so.

function removeMedia(){
    let videos = document.getElementsByTagName('video');
    for(let vid in videos){
        if(typeof videos[vid] == 'object'){
            let srcs = videos[vid].getElementsByTagName('source');
            videos[vid].pause();
            for(let xsrc in srcs){
                if(srcs[xsrc].src !== undefined){
                    srcs[xsrc].src = '';
                }
            }
            videos[vid].load();
            videos[vid].parentNode.removeChild(videos[vid]);
        }
    }
}

ok, here's a simple solution which certainly works:

var bodypage = document.getElementsByTagName('body')[0];
var control_to_remove = document.getElementById('id_of_the_element_here');
bodypage.removeChild(control_to_remove);

According to this bug:

https://bugs.chromium.org/p/chromium/issues/detail?id=255456&can=2&q=255456&colspec=ID%20Pri%20M%20Stars%20ReleaseBlock%20Component%20Status%20Owner%20Summary%20OS%20Modified

this seems to be a memory leak issue in Chrome!

var video = document.getElementById('video');
        if (video.firstChild) {
            video.removeChild(video.firstChild);
            video.load();
        }

I've encountered this problem on a more complicated level where we are loading ~80 videos on a page, and having problems with memory management in IE and Edge. I posted our solution on a similar question I asked specifically about our issue: https://stackoverflow.com/a/52119742/1253298

My code did not use a <video> element with a src tag, but instead used multiple <source> children to set a video in multiple formats.

To properly destroy and unload this video, I had to use a combination of multiple answers on this page, which resulted in:

var videoElement = $('#my-video')
videoElement[0].pause()  // Pause video
videoElement.empty()     // Remove all <source> children
videoElement.load()      // Load the now sourceless video
delete videoElement      // The call mentioned in other answers
videoElement.remove()    // Removing the video element altogether

Hope this helps someone.

Here is an answer on how to close the camera - not only pausing. It is the stream that should be stopped - not the video elements reference: stream.stop()

Not much complicated. Just put your src to null.

Eg: document.querySelector('#yourVideo').src = null;

It will remove your video src attribute. Done.

This is what I did to solve this problem. I created 2 video elements (video1 & video2). After finished using video1, get the source(src) attribute value and then remove video1 from DOM.

Then set video2 source (src) to whatever value you got from video1.

Do not use stream from video1 as it is cached in memory.

Hope this will help.

One solution that worked for me in AngularJS is using below code: In case you don't want to remove your source url, and reset to start of the video

let videoElement = $document[0].getElementById('video-id');
videoElement.pause();
videoElement.seekable.start(0);
videoElement.load();

And in case you want to remove the source from video tag:

let videoElement = $document[0].getElementById('video-id');
videoElement.pause();
videoElement.src="";
videoElement.load();

Hope someone finds it useful.

In my case, i used the solution mentioned above by @toon lite:

 Array.from(document.getElementsByTagName('video')).forEach(video => {
   video.pause();
   video.removeAttribute('src');
   video.load();
 })

But it occurs the another problem in Chrome browser (version 93):

[Intervention] Blocked attempt to create a WebMediaPlayer as there are too many WebMediaPlayers already in existence. See crbug.com/1144736#c27

I guess it is all about the browser version's limit (mine is too old), anyway i fixed this bug by adding some extra operations:

video.src = '';
video.srcObject = null;  
video.remove()

Finally the code looks like:

Array.from(document.getElementsByTagName('video')).forEach(video => {
  video.pause();
  video.removeAttribute('src'); // video.src = '' works so this line can be deleted
  video.load();
  video.src = '';
  video.srcObject = null;  
  video.remove()
})

In my case I have found that storing the reference to the video element, instead of finding it again in the DOM, makes it behave as expected. Since I am in a jQuery widget, I use this.options.videoElement, but you could use a global videoElement variable as well.

if (!this.options.videoElement) {

   var video = document.createElement('video');
   video.src = 'https://somevideo.mp4';
   video.type = 'video/mp4';
   video.muted = true;
   video.autoplay = true;

   this.options.videoElement = video;

   document.body.prepend(video);

}

Then when I want to control it:

this.options.videoElement.pause();

this.options.videoElement.remove();

I know this is an old question, but I came across the same issue, and tried almost every solution mentioning <video>'s src attribute, and all solutions seemed to have their drawbacks.

In my specify case, besides <video> elements, I am also using <audio> elements at the same time.

I was reading an article at MDN when I realized that dealing with the src attribute could be the wrong thing to do. Instead, I rewrote all my code to append and remove <source> elements to both <video> and <audio> elements.

That was the only way I found that does not trigger a new load or generates error or other undesirable notifications.

This is a minimal/simplified version of the code I am using (tested on Firefox 86 and Chrome 88).

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui, shrink-to-fit=no" />
</head>
<body>
    <button type="button" onclick="play()">Play</button>

    <button type="button" onclick="stop()">Stop</button>

    <video id="myVideo"></video>

    <script type="text/javascript">
        "use strict";

        var myVideo = document.getElementById("myVideo");

        myVideo.onloadstart = () => {
            console.log("onloadstart");
        };

        myVideo.onloadeddata = () => {
            console.log("onloadeddata");
        };

        myVideo.onload = () => {
            console.log("onload");
        };

        myVideo.onerror = () => {
            console.log("onerror");
        };

        function play() {
            while (myVideo.firstChild)
                myVideo.removeChild(myVideo.firstChild);

            var source = document.createElement("source");
            source.src = "example.mp4";
            myVideo.appendChild(source);
            myVideo.load();
            myVideo.play();
        }

        function stop() {
            while (myVideo.firstChild)
                myVideo.removeChild(myVideo.firstChild);

            myVideo.load();
        }
    </script>
</body>
</html>

本文标签: javascriptHow to properly unloaddestroy a VIDEO elementStack Overflow