I have been working with HTML5 and CSS3 for a long time now, but have avoided JavaScript because of my belief that it's most frequently used unnecessarily while having a tendency to be poorly written. So I held off until I needed to learn it to use something really cool and useful. The project that sold me was WebTorrent.
I do have programming experience (the most syntactically similar languages I know are PHP and Java), so I have some idea of standards, but I don't know best practices for JavaScript. The code certainly works and will be polished later on (it's more of a tech demo than anything), so I'd prefer critique on syntax and general methods more than function, unless I'm doing something fundamentally wrong.
I didn't go into this blind, as tempting as it was. My intro was MDN's A Re-Introduction to JavaScript, which I found very helpful. All this code is in the page's <head>, so if I should be moving it somewhere else or calling it on an element, please let me know.
<script src="https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script> <script> var client = new WebTorrent(); // Torrent ID var torrentId = 'redacted WebTorrent magnet link - contains 2 audio files, 1 video file, 1 image'; client.add(torrentId, function ontorrent(torrent){ /* Gameplan: Load Content (done by this point) Case empty torrent Case no playable media warn user break Case multiple playable media ask which file(s) to play Case one playable media play media break */ // Compatible Media Formats var MEDIA_EXT = ['mp4', 'm4v', 'm4v', 'webm', 'm4a', 'mp3', 'wav', 'aac', 'ogg', 'oga']; function getExt(name){ // Not own work: http://stackoverflow.com/questions/190852/how-can-i-get-file-extensions-with-javascript return name.substr((~-name.lastIndexOf(".") >>> 0) + 2); } // Status logger var logElement = document.getElementById('status'); function pStatus(msg){ logElement.innerHTML += "<br/>" + msg }; var numFiles = torrent.files.length; // Check for empty torrent if(numFiles == 0){ pStatus("No files found! Cannot render media.") return; } // Find all playable media var playable = new Array(); torrent.files.forEach(function(file){ pStatus(" - Found file: " + file.name); if(MEDIA_EXT.indexOf(getExt(file.name.toLowerCase())) > 0){ playable.push(file); } }); playable.forEach(function(file){ pStatus("File " + file.name + " is usable."); }); if(playable.length === 1){ playable[0].appendTo(document.getElementById('target')); }else{ do{ var index = window.prompt("Multiple files found. Please choose the index you would like to play."); }while(playable[index] == undefined); var file = playable[index]; pStatus("Choosing index " + index + ": " + file.name + "..."); file.appendTo(document.getElementById('target')); pStatus("Now loading " + file.name); document.title = file.name; } }); </script>