HTML5 Video and Audio Force-Fallback Javascript

Recently I have been looking on the web for a decent force-fallback script, but unfortunately I just couldn’t find a script that satisfies me, so I decided to write my own script.  The script below requires jQuery, which wordpress happens to include, I find the script almost perfect, it works on most browsers and it even works on mobile devices as well. If the script does not detect a compatible format it will do a force-fallback. I also included this script in one of my wordpress plugins (HTML Video and Audio Framework 1.7.0 and later)

jQuery('video').each(function() {
		var support = false;
		jQuery(this).children('source').each(function() {
			if(support == false) {
				var type = jQuery(this).attr('type');
				try {
					support = document.createElement('video').canPlayType(type);
					if(support == "") {
						support = false;
					}
				} catch (e) {
					// Do nothing
				}
			}
		} )
		if(support == false) {
			jQuery(this).children('source').remove();
			jQuery(this).children().insertBefore(this);
			jQuery(this).remove();
		}
	}
)

jQuery('audio').each(function() {
		var support = false;
		jQuery(this).children('source').each(function() {
			if(support == false) {
				var type = jQuery(this).attr('type');
				try {
					support = !!document.createElement('audio').canPlayType(type);
					if(support == "") {
						support = false;
					}
				} catch (e) {
					// Do nothing
				}
			}
		} )
		if(support == false) {
			jQuery(this).children('source').remove();
			jQuery(this).children().insertBefore(this);
			jQuery(this).remove();
		}
	}
)

The script does not care about the class name or the id, all it cares about is the element (video and audio) and the type attribute in source element.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>