Using MediaelementJS in Rails

Based on the information on the site, the integration of this mediaplayer seems to be simple enough: You just need to copy over a JavaScript file to Rails’ JS folder and a stylesheet to the corresponding folder in assets. If you are not using jQuery in your app yet, you also either need to put jQuery in the JS folder – or integrate a CDN version in your application.html.erb layout (see “Using jQuery with a CDN”), for example. In this case, I used a locally installed version of jQuery, while on previous projects I usually used the CDN version – both generally work fine. What was unclear (at least for a Rails beginner like me) is where to put the image files that make up the controls of MediaelementJS.

Nevertheless, I got MediaelementJS to work “50% of the time, all the time”, with just these basic steps, right out of the box – albeit with missing images of the controls. The 50% of the time where a problem though, and having a visible play button etc. also would be “good”, so some “fixing” was necessary.

After some trial-and-error, I got MediaelementJS to find it’s button images – but only when I put them in the root directory of my app. In hindsight, I think I simply put the path together the wrong way, when trying to get the mediaelementplayer.css to point to the app/assets/images or the public folder of my app, for example. While the assets/images folder is indeed where I put the bottons in the end now, neither is a good solution as such though, as I learned through finding this Q&A on Stack Overflow and asking at OpenTech School‘s Ruby learners meetup. My app would be okay in development mode, but the links to the images would break in production. What needs to be done is to change mediaelementJS’ CSS to an SCSS file and change the URLs referenced in it from ” url(somefile.png) ” to ” asset-url(somefile.png) “ – and Sprocket will take care of things.

The “50% problem” was a second, unrelated problem and not fixed by this. My app would have the strange behavior that it would use the native media player of the browser on the first load of a page with a video and the MediaelementJS only after one F5 reload (and following reloads). In this case, the fix was not the “proper way”: The javascript_include_tag in the application.html.erb was moved from the header of the site to just before the end </body> tag. The jQuery of mediaelementJS previously was just executed too early, before the document was ready. A better (performing) solution would probably have been to just move the loading of the relevant Javascript (mediaelement-and-player.min.js), however, this also works and was “good enough” for now.

Thanks to Jose from OTS for answering my questions! I been to told that this Railscast should be helpful to understand the Asset Pipeline (that makes these URL changes necessary) better – haven’t watched it myself yet though. Feedback on this post? Write me on Twitter.