yepnope.js是一个超高速的按条件异步加载资源的加载器,允许你只加载使用到的资源(css及js)。
yepnope({
test : Modernizr.geolocation,
yep : 'normal.js',
nope : ['polyfill.js', 'wrapper.js']
});
此实例表示如果Modernizr.geolocation为真的时候加载normal.js,为假则加载polyfill.js及wrapper.js。
yepnope([{
test : /* boolean(ish) 输入条件 */,
yep : /* array (of strings) | string - 条件为真时加载的资源 */,
nope : /* array (of strings) | string - 条件为假时加载的资源 */,
both : /* array (of strings) | string - 条件无论真假都加载 */,
load : /* array (of strings) | string - 条件无论真假都加载 */,
callback : /* function ( testResult, key ) | object { key : fn } 回调函数 */,
complete : /* function 加载完成后执行的函数 */
}, ... ]);
为什么使用yepnope:
yepnope([{
load: 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
complete: function () {
if ( ! window.jQuery ) {
yepnope( 'local/jquery.min.js' );
}
}
},
{
load : 'jquery.plugin.js',
complete: function () {
jQuery(function () {
jQuery( 'div' ).plugin();
});
}
}
]);
而其他加载器则可能必须这样处理:
someLoader('http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js', function(){if ( ! window.jQuery ) {
someLoader( 'local/jquery.min.js', 'jquery.plugin.js' );
/*注意这点和yepnope的区别,yepnope加载失败后仅需重新加载备用资源即可,不会影响依赖此资源的其他文件执行*/
} else {
someLoader( 'jquery.plugin.js' );
}
});
yepnope的不足
yepnope( '/url/to/your/script.js' );
yepnope( {
load : '/url/to/your/script.js'
} );
yepnope( {
test : window.JSON,
load : '/url/to/your/script.js',
callback : function ( url, result, key ) {
// whenever this runs, your script has just executed.
alert( 'script.js has loaded!' );
}
} );
yepnope( {
test : window.JSON,
nope : 'json2.js',
complete : function () {
var data = window.JSON.parse( '{ "json" : "string" }' );
}
} );
yepnope( {
test : Modernizr.geolocation,
yep : {
'rstyles' : 'regular-styles.css'
},
nope : {
'mstyles' : 'modified-styles.css',
'geopoly' : 'geolocation-polyfill.js'
},
callback : function ( url, result, key ) {
if ( key === 'geopoly' ) {
alert( 'This is the geolocation polyfill!' );
}
}
} );
yepnope( {
test : Modernizr.geolocation,
yep : {
'rstyles' : 'regular-styles.css'
},
nope : {
'mstyles' : 'modified-styles.css',
'geopoly' : 'geolocation-polyfill.js'
},
callback : {
'rstyles' : function ( url, result, key ) {
alert( 'This is the regular styles!' );
},
'mstyles' : function ( url, result, key ) {
alert( 'This is the modified styles!' );
},
'geopoly' : function ( url, result, key ) {
alert( 'This is the geolocation polyfill!' );
}
},
complete : function () {
alert( 'Everything has loaded in this test object!' );
}
} );
yepnope( 'css!mystyles.php?version=1532' );
yepnope( {
load : 'preload!jquery.1.5.0.js',
callback : function ( url, result, key ) {
window.jQuery; //undefined
yepnope(jquery.1.5.0.js);
window.jQuery; //object
}
} );
yepnope({load: ['normal.js', 'ie6!ie7!ie-patch.js'] // ie6 or ie7 only (on patch)
});
来自:http://www.au92.com/archives/yepnope-js.html