resLoader.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. (function (root, factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. //AMD
  4. define(factory);
  5. } else if (typeof exports === 'object') {
  6. //Node, CommonJS之类的
  7. module.exports = factory();
  8. } else {
  9. //浏览器全局变量(root 即 window)
  10. root.resLoader = factory(root);
  11. }
  12. }(this, function () {
  13. var isFunc = function(f){
  14. return typeof f === 'function';
  15. }
  16. //构造器函数
  17. function resLoader(config){
  18. this.option = {
  19. resourceType : 'image', //资源类型,默认为图片
  20. baseUrl : './', //基准url
  21. resources : [], //资源路径数组
  22. onStart : null, //加载开始回调函数,传入参数total
  23. onProgress : null, //正在加载回调函数,传入参数currentIndex, total
  24. onComplete : null //加载完毕回调函数,传入参数total
  25. }
  26. if(config){
  27. for(i in config){
  28. this.option[i] = config[i];
  29. }
  30. }
  31. else{
  32. alert('参数错误!');
  33. return;
  34. }
  35. this.status = 0; //加载器的状态,0:未启动 1:正在加载 2:加载完毕
  36. this.total = this.option.resources.length || 0; //资源总数
  37. this.currentIndex = 0; //当前正在加载的资源索引
  38. };
  39. resLoader.prototype.start = function(){
  40. this.status = 1;
  41. var _this = this;
  42. var baseUrl = this.option.baseUrl;
  43. for(var i=0,l=this.option.resources.length; i<l; i++){
  44. var r = this.option.resources[i], url = '';
  45. if(r.indexOf('http://')===0 || r.indexOf('https://')===0){
  46. url = r;
  47. }
  48. else{
  49. url = baseUrl + r;
  50. }
  51. var image = new Image();
  52. image.onload = function(){_this.loaded();};
  53. image.onerror = function(){_this.loaded();};
  54. image.src = url;
  55. }
  56. if(isFunc(this.option.onStart)){
  57. this.option.onStart(this.total);
  58. }
  59. }
  60. resLoader.prototype.loaded = function(){
  61. if(isFunc(this.option.onProgress)){
  62. this.option.onProgress(++this.currentIndex, this.total);
  63. }
  64. //加载完毕
  65. if(this.currentIndex===this.total){
  66. if(isFunc(this.option.onComplete)){
  67. this.option.onComplete(this.total);
  68. }
  69. }
  70. }
  71. //暴露公共方法
  72. return resLoader;
  73. }));