How jQuery mobile violates the DOM

I’ve grown to be a big fan of component libraries that convert HTML to rich javascript, such as Chosen and Select2. One reason is because they are minimally invasive. When the component is created, it resides next to the original HTML element and allows you to interface with it via the same events and attributes.

Recently while attempting to use jQuery mobile components with a backbone application, I began to have problems. Backbone views allow for a section of the dom to be manipulated and re-rendered using the $el variable:

render: ->
  @setElement Mustache.to_html(@template, { message: "Welcome home" })
  console.log "Page: #{@name}, was just inserted into the dom!"

With nice libraries such as Chosen, Select2, and even Bootstrap this pattern works fine, because the created components reside on the same level of the DOM as the original HTML elements. However, jQuery mobile violates this pattern by placing the elements at the top of the page layout. One possible reason for this is that jQuery mobile is based on jQuery UI, which also violated the DOM when creating modal and other components. Another possible reason is that the idea behind jQuery mobile is to encapsulate each page. JQuery mobile wants to handle page rendering and caching, which actually doesn’t play nice in general with Backbone JS.

Overall, my advice to anyone looking to create an HTML/JavaScript based phone app is to stay away from jQuery mobile and rely on components that can be easily removed from the DOM and recreated.