You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

72 lines
2.6 KiB

  1. /** @license
  2. * RequireJS plugin for loading JSON files
  3. * - depends on Text plugin and it was HEAVILY "inspired" by it as well.
  4. * Author: Miller Medeiros
  5. * Version: 0.4.0 (2014/04/10)
  6. * Released under the MIT license
  7. */
  8. define(['text'], function(text){
  9. var CACHE_BUST_QUERY_PARAM = 'bust',
  10. CACHE_BUST_FLAG = '!bust',
  11. jsonParse = (typeof JSON !== 'undefined' && typeof JSON.parse === 'function')? JSON.parse : function(val){
  12. return eval('('+ val +')'); //quick and dirty
  13. },
  14. buildMap = {};
  15. function cacheBust(url){
  16. url = url.replace(CACHE_BUST_FLAG, '');
  17. url += (url.indexOf('?') < 0)? '?' : '&';
  18. return url + CACHE_BUST_QUERY_PARAM +'='+ Math.round(2147483647 * Math.random());
  19. }
  20. //API
  21. return {
  22. load : function(name, req, onLoad, config) {
  23. if (( config.isBuild && (config.inlineJSON === false || name.indexOf(CACHE_BUST_QUERY_PARAM +'=') !== -1)) || (req.toUrl(name).indexOf('empty:') === 0)) {
  24. //avoid inlining cache busted JSON or if inlineJSON:false
  25. //and don't inline files marked as empty!
  26. onLoad(null);
  27. } else {
  28. text.get(req.toUrl(name), function(data){
  29. var parsed;
  30. if (config.isBuild) {
  31. buildMap[name] = data;
  32. onLoad(data);
  33. } else {
  34. try {
  35. parsed = jsonParse(data);
  36. } catch (e) {
  37. onLoad.error(e);
  38. }
  39. onLoad(parsed);
  40. }
  41. },
  42. onLoad.error, {
  43. accept: 'application/json'
  44. }
  45. );
  46. }
  47. },
  48. normalize : function (name, normalize) {
  49. // used normalize to avoid caching references to a "cache busted" request
  50. if (name.indexOf(CACHE_BUST_FLAG) !== -1) {
  51. name = cacheBust(name);
  52. }
  53. // resolve any relative paths
  54. return normalize(name);
  55. },
  56. //write method based on RequireJS official text plugin by James Burke
  57. //https://github.com/jrburke/requirejs/blob/master/text.js
  58. write : function(pluginName, moduleName, write){
  59. if(moduleName in buildMap){
  60. var content = buildMap[moduleName];
  61. write('define("'+ pluginName +'!'+ moduleName +'", function(){ return '+ content +';});\n');
  62. }
  63. }
  64. };
  65. });