Question

What is the best way to make use of webshims in a backbone project? Is there a way to avoid using it globally and only loading it for a specific view?

Was it helpful?

Solution

Yes this is possible. But I would always include the modernizr and polyfiller.js in the base setup.

In case you are doing this you should configure at least waitReady and basePath:

webshims.setOptions({ waitReady: false, basePath: "/js/libs/shims/" });

Your code for your view could look like this:

Backbone.View.extend({

  initialize: function(){
    //Load webshims
    webshims.polyfill('forms forms-ext mediaelement');
  },

  render: function() {
    this.$el.html( this.template(this.model.attributes) );
    //update new created elements
    this.$el.updatePolyfill();
    return this;
  }

});

Normally webshims delays jQuery's 'ready' event until all features are implented. In case you want to use webshims only in a specific view you can't delay it. In case you want to use the polyfilled JS/DOM API. You should wrap your JS code, which uses those APIs in a webshims.ready callback:

render: function() {
    var thisObject = this;
    this.$el.html( this.template(this.model.attributes) );
    //update new created elements
    this.$el.updatePolyfill();

    //wait until video API is implemented and then use it
    webshims.ready('mediaelement', function(){
        $('video', thisObject.$el).play();
    });
    return this;
}

In case you want to speed up things, you can load it inside your view and after window.load:

   $(window).on('load', function(){
      //preload after onload
      webshims.polyfill('forms forms-ext mediaelement');
   });

This way webshims is loaded either as soon as the view starts to initialize or after onload. webshims might give you a warning in this case, that you have called it twice, but this won't hurt.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top