Appending HTML5 Video tags with jQuery

I just found an interesting jQuery bug. I was creating a <video> tag via jQuery, including the src attribute, and appending it to my container, like this:

$("#videoWrapper").append($("<video id='myVideo' src='video1.mp4'  />"));

This worked and the video played fine, but when I was debugging in Fiddler I found it was actually downloading the video twice!   It must be activating the tag somehow during the append process.  That’s not so good for performance.

The fix was to add the src attribute afterwards:

$("#videoWrapper").append($("<video id='myVideo' />"));
$("#myVideo").attr('src', 'video1.mp4');

There are probably some other ways to address it as well, but this worked!

Advertisements

3 thoughts on “Appending HTML5 Video tags with jQuery

  1. sorry but this either didnt work can u suggest me what hav i done wrong here….
    jQuery(“button”).click(function(){
    jQuery(“#dev”).append($(“”));
    jQuery(“#myvideo”).attr(‘src’,’http://www.youtube.com/watch?v=_crpeJY5e44′);
    });

  2. jQuery(“button”).click(function(){
    jQuery(“#dev”).append($(“”));
    jQuery(“#myvideo”).attr(‘src’,’http://www.youtube.com/watch?v=_crpeJY5e44′);
    });
    sorry it was mistyped

    • I see 2 issues:

      1. Your second line isn’t actually appending a video tag — you are appending an empty string. Unless #myvideo already exist somewhere on your page, you won’t have a video tag to work with.

      2. I don’t believe you can use a youtube URL as the source of your video file. That URL returns a YouTube player (which should be put in an IFRAME or something). The source of a video tag should be an .mp4, .mov, .ogg, or other actual video file.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s