text.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. //
  7. // dojo text! plugin
  8. //
  9. // We choose to include our own plugin in hopes of leveraging functionality already contained in dojo
  10. // and thereby reducing the size of the plugin compared to various loader implementations. Naturally, this
  11. // allows AMD loaders to be used without their plugins.
  12. // CAUTION, this module may return improper results if the AMD loader does not support toAbsMid and client
  13. // code passes relative plugin resource module ids. In that case, you should consider using the text! plugin
  14. // that comes with your loader.
  15. define(["dojo", "dojo/cache"], function(dojo){
  16. var
  17. cached= {},
  18. cache= function(cacheId, url, value){
  19. cached[cacheId]= value;
  20. dojo.cache({toString:function(){return url;}}, value);
  21. },
  22. strip= function(text){
  23. //note: this function courtesy of James Burke (https://github.com/jrburke/requirejs)
  24. //Strips <?xml ...?> declarations so that external SVG and XML
  25. //documents can be added to a document without worry. Also, if the string
  26. //is an HTML document, only the part inside the body tag is returned.
  27. if(text){
  28. text= text.replace(/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, "");
  29. var matches= text.match(/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im);
  30. if(matches){
  31. text= matches[1];
  32. }
  33. }else{
  34. text = "";
  35. }
  36. return text;
  37. };
  38. return {
  39. load:function(id, require, load){
  40. var match, cacheId, url, parts= id.split("!");
  41. if(require.toAbsMid){
  42. match= parts[0].match(/(.+)(\.[^\/]*)$/);
  43. cacheId= match ? require.toAbsMid(match[1]) + match[2] : require.toAbsMid(parts[0]);
  44. if(cacheId in cached){
  45. load(parts[1]=="strip" ? strip(cached[cacheId]) : cached[cacheId]);
  46. return;
  47. }
  48. }
  49. url= require.toUrl(parts[0]);
  50. dojo.xhrGet({
  51. url:url,
  52. load:function(text){
  53. cacheId && cache(cacheId, url, text);
  54. load(parts[1]=="strip" ? strip(text) : text);
  55. }
  56. });
  57. },
  58. cache:function(cacheId, mid, type, value) {
  59. cache(cacheId, require.nameToUrl(mid) + type, value);
  60. }
  61. };
  62. });