所以我同意 AMD 评论(不能将代码阻塞放入评论中,嗯……)
这是我为 FileSaver.js 所做的
首先在我的 requirejs config / main.js :
(function() {
// REMEMBER TO DUPLICATE CHANGES IN GRUNTFILE.JS
requirejs.config({
paths: {
"jquery": "PATH/jquery.min", // NO .js
"lib.filesaver" : "PATH/FileSaver", // NO .js
"shim.blob" : "PATH/Blob" // NO .js
},
shim: {
"lib.filesaver": {deps: ["shim.blob"]}
}
});
define([
"jquery"
], function(
$
) {
$(document).ready(function() {
// start up code...
});
return {};
});
})();
然后我将 Blob.js/jquery 和 Filersaver 放在正确的位置
我还为 pre IE10 创建了一个 IEShim
define([], function () {
/**
* @class IEshims
* container for static IE shim functions
*/
var IEShims = {
/**
* saveFile, pops up a built in javascript file as a download
* @param {String} filename, eg doc.csv
* @param {String} filecontent eg "this","is","csv"
*/
saveAs: function (filename, filecontent, mimetype ) {
var w = window.open();
var doc = w.document;
doc.open( mimetype,'replace');
doc.charset = "utf-8";
doc.write(filecontent);
doc.close();
doc.execCommand("SaveAs", null, filename);
}
};
return IEShims;
});
最后,当我想使用 Filesaver 时,将其设为必需(与 IEShim 一起用于不良浏览器)
define([
"lib.filesaver",
"IEShims"
],
function (
FileSaver, // it's empty, see saveAs global var
IEShims
) {
...
var fileName = "helloworld.txt";
var fileContents = "Me haz file contents, K Thx Bye";
var mimeType = "text/plain";
if(saveAs) {
var blob = new Blob(
[fileContents],
{type: mimeType + ";charset=" + document.characterSet}
);
saveAs(blob, fileName);
} else {
IEShims.saveAs(fileName, fileContents,mimeType );
}
...
};