Posted By

kif on 07/26/06


Tagged

file load jsfile


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

alvaroisorna
vali29


JS File Loader


 / Published in: JavaScript
 

Support: Fx2, Opera9, IE6

  1. /*-----------------------------------------------------------------------------
  2.  * JS File Loader
  3.  * Example Source
  4. <script type="text/javascript" src="/js/Foo.js"></script>
  5. <script type="text/javascript" src="/files/Bar.js?load=Baz,Qux"></script>
  6. <script type="text/javascript" src="/files/Qux.js?date=20060727"></script>
  7. var loader = new JSFile();
  8. loader('Foo,Bar,Baz'.split(','), '/lib/')
  9.  * load files is
  10.  * - /js/Foo.js
  11.  * - /files/Bar.js
  12.  * - /files/Baz.js
  13.  * - /files/Qux.js // NOT double load
  14.  * - /lib/Foo.js
  15.  * - /lib/Bar.js
  16.  * - /lib/Baz.js
  17.  *-------------------------------------------------------------------------- */
  18.  
  19. function JSFile() {
  20. var scripts = document.getElementsByTagName('script');
  21. this.base = scripts[0];
  22. this.list = {};
  23. this.book = {};
  24.  
  25. for (var i = 0, len = scripts.length; i < len; ++i) {
  26. var src = scripts[i].getAttribute('src');
  27. if (!src) continue;
  28. this.list[src] = true;
  29. var path = src.replace(/([^\/]+?)\.js(\?.*)?$/, ''), inc = src.match(/\?.*load=([^&]*)/);
  30. if (inc) {
  31. if (path in this.book)
  32. this.book[path] += ',';
  33. else
  34. this.book[path] = '';
  35. this.book[path] += inc[1];
  36. }
  37. }
  38. for (var path in this.book)
  39. this.load(this.book[path].split(','), path);
  40. }
  41.  
  42. JSFile.prototype = {
  43. _load: function (uri) {
  44. var XUL_NS_URI = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';
  45. if (document.documentElement &&
  46. document.documentElement.namespaceURI == XUL_NS_URI) {
  47. var tmp = document.createElementNS(XUL_NS_URI, 'script');
  48. tmp.setAttribute('type', 'application/x-javascript');
  49. tmp.setAttribute('src', uri);
  50. this.base.parentNode.appendChild(tmp);
  51. } else {
  52. document.write('<script type="text/javascript" src="' + uri +'"></script>');
  53. }
  54. },
  55. load: function (jsfile, prefix, suffix) {
  56. prefix = prefix || '';
  57. suffix = suffix || '.js';
  58. for (var i = 0, len = jsfile.length; i < len; ++i) {
  59. var path = prefix + jsfile[i] + suffix;
  60. if (!this.list[path]) this._load(path);
  61. }
  62. }
  63. }

Report this snippet  

You need to login to post a comment.