preloading.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. function preloadFile(file, onLoadCallback){
  2. var r = new XMLHttpRequest();
  3. r.open("GET", file, true);
  4. r.responseType = "arraybuffer";
  5. r.onload = onLoadCallback;
  6. r.send();
  7. }
  8. var _preloadingCounter = 0;
  9. function isPreloading(){
  10. return _preloadingCounter != 0;
  11. }
  12. function createFolder(path)
  13. {
  14. var r = "";
  15. var t = path.split("/");
  16. for (var n=0; n < t.length - 1; ++n)
  17. {
  18. try
  19. {
  20. r = "";
  21. for (var i = 0; i <= n; ++i){
  22. r += "/" + t[i];
  23. }
  24. FS.mkdir(r);
  25. } catch(e){
  26. var q= 0;
  27. }
  28. }
  29. return {"folder":r, "file":t[t.length - 1]};
  30. }
  31. function Preloading(id){
  32. return {
  33. _num:0,
  34. _loaded:0,
  35. _id:id,
  36. _done:function(){
  37. //var f = Module.cwrap('fromjs_preloaded', 'void', ['string']);
  38. //f(this._id);
  39. _preloadingCounter -=1;
  40. },
  41. add: function(path){
  42. console.log("preloading " + path);
  43. this._num += 1;
  44. var self = this;
  45. //t += "/";
  46. preloadFile("data/" + path, function(e){
  47. var result = new Uint8Array(e.currentTarget.response);
  48. createFolder(path);
  49. FS.writeFile(path, result, {encoding:'binary'});
  50. self._loaded += 1;
  51. if (self._loaded == self._num){
  52. self._done.apply(self);
  53. }
  54. });
  55. },
  56. start: function(){
  57. _preloadingCounter +=1;
  58. }
  59. }
  60. }
  61. function preload_file(path){
  62. var p = Preloading(path);
  63. p.add(path);
  64. p.start();
  65. }