Video still playing after removal from DOM, how to eliminate completely?

2.1k Views Asked by At

I have a container on my site where I dynamically inject new content via jQuery Ajax/XHR whenever a certain type of link is clicked.

For some pages this container holds a grid with multiple HTML5 <video> elements playing in a loop.

At a certain point I was experiencing increasing performance drops after a few XHR requests which replace content inside the container. After unmuting my videos, I recognized only through the Audio coming from my speakers that they actually keep playing, even if they are completely removed from the DOM(which means I had tons of videos playing after a few XHR replacements within my container, videos which actually aren’t in the DOManymore).

I tried a few things now, none of which seem to help:

  • Using jQuery’s .remove() on all videos before the XHR request to remove the videos from the DOM before I inject new content
  • Pausing the videos via Javascript before loading new content

This only seems to work randomly, which drives me crazy. Sometimes some or alle videos keep playing somewhere from the off, overlapping with the new video content. Also, they are not showing up in Chrome DevTool’S Network Tab …

I have the feeling that due to buffering stuff just classic DOM-querying and manipulation doesn’t work here … Any hint of what I could put into my pre-XHR request function to make sure ANY current <video> content from the DOM (and off, in the buffer and elsewhere) is really a 100% removed, in other words 'killed’?

EDIT: Here is a simplified demo of my problem, try clicking the links which exchange the content of the div with the ID #content http://www.letrip.de/html5video-problem/

You can see the Javascript by adding /js/app.js to the URL

3

There are 3 best solutions below

6
On BEST ANSWER

change:


    var content = $(data).find('#content');
    html = content.html();
    $('#content').html(html);

to:


     var = content = $("#content",data);
     $('#content').html(content);

Best regards

UPDATE As soon as you do this: $(data) the problem will return. Try to do this to return the title:


     var titledata = data.match("(.*?)")[1];
     console.log(titledata);

5
On

Add video as a template.. and assign this template to a variable and use it, make it null when you want to remove it.

Ex. Var vdo=

Do your manipulations and then make it null

Vdo = null;

1
On

Just adding what worked for me, i had couple of videos in container and even after completely removing container from the DOM, video sound kept playing.

I even tried to remove video elements from the dom before removing container, but it didn't help.

Here is what worked for me.

Step 1 - Set src property to empty string instead of removing it

This won't work -

video.removeAttribute("src");

This will work

video.src="";

Step 2 - Load video Once you have set src to empty string simply call video.load().

In short

video.src="";
video.load();