-
-
Save wjcrowcroft/1266562 to your computer and use it in GitHub Desktop.
RequireJS plugin for loading JSON files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* RequireJS plugin for loading JSON files | |
* - depends on Text plugin and it was HEAVILY "inspired" by it as well. | |
* | |
* IMPORTANT: it only works on r.js optimizer after version 0.26+ 20011/09/27 | |
* | |
* @author Miller Medeiros | |
* @version 0.0.1 (2011/06/10) | |
* Released under the WTFPL <http://sam.zoy.org/wtfpl/> | |
*/ | |
define(['text'], function(text){ | |
var jsonParse = (typeof JSON !== 'undefined' && typeof JSON.parse === 'function')? JSON.parse : function(val){ | |
return eval('('+ val +')'); //quick and dirty | |
}, | |
buildMap = {}; | |
//API | |
return { | |
load : function(name, req, onLoad, config) { | |
// Append '.json' if no filename given: | |
if (name.indexOf('.') < 0) { | |
name += ".json" | |
} | |
text.get(req.toUrl(name), function(data){ | |
if (config.isBuild) { | |
buildMap[name] = data; | |
onLoad(data); | |
} else { | |
onLoad(jsonParse(data)); | |
} | |
}); | |
}, | |
//write method based on RequireJS official text plugin by James Burke | |
//https://github.com/jrburke/requirejs/blob/master/text.js | |
write : function(pluginName, moduleName, write){ | |
if(moduleName in buildMap){ | |
var content = buildMap[moduleName]; | |
write('define("'+ pluginName +'!'+ moduleName +'", function(){ return '+ content +';});\n'); | |
} | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just for the use case in our app, it made sense that paths without '.json' needed to have it appended:
Only really for aesthetics and I don't like seeing 'json' repeated so many times..
Use with care though, as with any method of appending filetypes.
NB: typo in #22, should read "...if no filetype given"