I wrote JavaScript library to use FileSaver.js and its associated libraries. However, I don\'t want to always load FileSaver.js whenever someone wants to use my library. And
So I agree with the AMD comment (can't put code blocking into comments meh...)
Here's what I do for FileSaver.js
First in my 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 {};
});
})();
Then I place the Blob.js/jquery and Filersaver in correct places
I also created a IEShim for pre IE10
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;
});
And lastly when I want to use Filesaver make it required (along with IEShim for bad browsers)
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 );
}
...
};