如何正确卸载/销毁视频元素

我正在开发一个实时媒体浏览/回放应用程序,它使用浏览器中的 <video>对象进行回放。

我混合使用了 javascript 和 jQuery,

我特别关心的是记忆。应用程序从不在窗口中重新加载,用户可以观看许多视频,因此随着时间的推移,内存管理成为一个大问题。在今天的测试中,我看到内存配置文件随着每次后续加载流的视频大小而跳跃,并且永远不会下降到基线。

我尝试了以下几种方法,结果都是一样的:

清空包含已创建元素的父容器,例如:

$(container_selector).empty();

2-暂停并删除匹配“ video”的子级,然后清空父容器:

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

还有其他人遇到过这个问题吗? 还有更好的解决办法吗?

101221 次浏览

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.

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();

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);

To reset the video to Blank without removing it

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

It stops the video

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.

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.

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()

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.

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

Not much complicated. Just put your src to null.

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

It will remove your video src attribute. Done.

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

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.

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.

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>

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]);
}
}
}

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()
})