问题
How come this alerts both, yes and false?
Modernizr.load([
{
test: Modernizr.cssgradients,
yep: alert('Supports it!'),
nope: alert('Oh, damn! This browser sucks!')
}
]);
I'm using the latest chrome on OS X.
回答1:
Because you're calling alert() directly there, and the result from alert() (always undefined) is assigned to the yep and nope properties. You need to wrap alert() in a function and assign that function instead:
Modernizr.load([
{
test: Modernizr.cssgradients,
yep: function () { alert('Supports it!') },
nope: function () { alert('Oh, damn! This browser sucks!') }
}
]);
This still won't work because it's not how yepnope works. yep and nope should be paths to JS files that are loaded:
Modernizr.load([
{
test: Modernizr.cssgradients,
nope: 'cssgradients-shim.js' //-> load a JS file to draw your gradients
}
]);
As you discovered yourself, if you don't want to use the integrated yepnope.js, you can just use Modernizr the traditional way:
if (!Modernizr.cssgradients) {
alert('Oh, damn! This browser sucks!');
}
回答2:
With yepnope prefixes, it's possible to run predefined, named functions. Note: I have only tested this with latest chrome on OS X.
However, for this to work, you will need a "dummy URL", e.g., an image that you plan to load on the page (your logo is a good candidate).
Also, because Modernizr.load only aliases the yepnope.apply method, you will need to refer to yepnope by name to add a prefix.
/*globals window */
(function (Modernizr) {
"use strict";
window.yepnope.addPrefix('function', function (resourceObj) {
var dummyUrl = 'static/my_logo.png';
resourceObj.noexec = true;
window[resourceObj.url]();
resourceObj.url = dummyUrl;
return resourceObj;
});
// predefined functions
window.alert_support = function () {
window.alert('Supports it!');
};
window.alert_damn = function () {
window.alert('Oh, damn! This browser sucks!');
};
window.alert_boom = function () {
window.alert('boom');
};
// Modernizer.load is an alias for yepnope. See API at http://yepnopejs.com/.
Modernizr.load([{
test: Modernizr.cssgradients,
yep: 'function!alert_support',
nope: 'function!alert_damn'
}, {
test: Modernizr.rgba,
yep: 'function!alert_boom'
}]);
}(window.Modernizr));
Of course, if you don't want to pollute the global window namespace, you could put your named functions in an object and change window[resourceObj.url](); to window.MyObj[resourceObj.url]();.
The real power of this is that callback functions fire, the named functions can call Modernizr.load as well, and/or you could write a more purposeful prefix than the generic function executor shown here.
回答3:
The yep and nope parameters do not accept functions as arguments. They should be a string or an array of strings indicating scripts to load based on whether the test succeeded or failed. See the documentation on Modernizr.load for more information.
来源:https://stackoverflow.com/questions/7808585/modernizr-testing