resLoader.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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(/^(\/|http(s?):\/\/)/.test(r)){
  46. url = r;
  47. } else {
  48. url = baseUrl + r;
  49. }
  50. var image = new Image();
  51. image.onload = function(){_this.loaded();};
  52. image.onerror = function(){_this.loaded();};
  53. image.src = url;
  54. }
  55. if(isFunc(this.option.onStart)){
  56. this.option.onStart(this.total);
  57. }
  58. }
  59. resLoader.prototype.loaded = function(){
  60. if(isFunc(this.option.onProgress)){
  61. this.option.onProgress(++this.currentIndex, this.total);
  62. }
  63. //加载完毕
  64. if(this.currentIndex===this.total){
  65. if(isFunc(this.option.onComplete)){
  66. this.option.onComplete(this.total);
  67. }
  68. }
  69. }
  70. //暴露公共方法
  71. return resLoader;
  72. }));