Safari iOS Specs Unobtrusive JavaScript Reminder
Recently I was digging around in the Safari Developer Library when I came across one more reason (as if there weren’t enough) to write Unobtrusive JavaScript. In this case, Safari on iOS (all devices) disables preload="" and autoplay="", in case the user may be in a position where they are on a horrid network and are being charged per data unit. So no data is actually loaded until initated by the user; this also implies that the play() and the load() methods are inactive until user initiated playback, unless the play() or load() method is triggered via user action. So in laymens terms, user-initiated Play buttons work, however the onload="play()" event does not. Safari Developer Library provided the solution below:
The example below does nothing in iOS:
<body onload="document.myMovie.play()">
The example below will play the media in iOS:
<input type="button" value="Play" onclick="document.myMovie.play()">
This works as-is, however the event handler is still mixed in with the markup thus violating the Seven Rules of Unobtrusive JavaScript, specifically number five:
5. Understand Events (Event handling to initiate change)
Event handling is the next step to truly Unobtrusive JavaScript…understand that Event Handling is true separation.
So I rewrote the Safari solution using Web Standards and separated behavior (JavaScript) from structure (html) using Unobtrusive JavaScript. I don’t have any video files available for the demo so I swapped audio in its place, as well as added some updated (read: “proper”) markup, but the principle(s) are not lost. The demo is a media control that will play a media file after user-initiated contact with the play button. You can view the demo here or view the code and markup below:
// javascript
window.onload = function() {
// Get the play button and append the audio play method to on click
var audio = document.getElementById("audiosrc");
var play = document.getElementById('play');
play.addEventListener('click', function(){
audio.play(); }, false);
}
<!-- html -->
<button type="button" id="play">
<audio id="audiosrc">
<source src="http://dev.bowdenweb.com/a/m/a/clipping_link-finds-a-secret-13908.ogg" />
<source src="http://dev.bowdenweb.com/a/m/a/clipping_link-finds-a-secret-13908.mp3" />
<source src="http://dev.bowdenweb.com/a/m/a/clipping_link-finds-a-secret-13908.wav" />
</audio>
</button>