0

在骨干项目中使用 webshim 的最佳方法是什么?有没有办法避免全局使用它并且只为特定视图加载它?

4

1 回答 1

1

是的,这是可能的。但我总是会在基本设置中包含modernizr 和polyfiller.js。

如果您这样做,您应该至少配置 waitReady 和 basePath:

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

您的视图代码可能如下所示:

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;
  }

});

通常 webshims 会延迟 jQuery 的“就绪”事件,直到所有功能都实现。如果您只想在特定视图中使用 webshim,则不能延迟它。如果你想使用 polyfill 的 JS/DOM API。您应该包装您的 JS 代码,该代码在 webshims.ready 回调中使用这些 API:

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;
}

如果你想加快速度,你可以在你的视图中和 window.load 之后加载它:

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

这样,webshims 会在视图开始初始化时或在 onload 后立即加载。在这种情况下,webshims 可能会给你一个警告,你已经调用了它两次,但这不会有什么坏处。

于 2013-11-14T22:13:24.517 回答