lazyload.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /**
  2. * Created by kiki on 2017/6/19.
  3. * 延迟加载
  4. */
  5. (function () {
  6. var options = {
  7. loadTaskMaxNum: 5 //延迟加载同时读取接口最大进程数
  8. };
  9. var lazyWaitQueue = new Array(); //延迟加载等待的队列
  10. var lazyProcessList = new Array(); //延迟加载读取中的列表
  11. //当前加载器状态
  12. var lazyLoadStatus = {
  13. currentTaskLoadNum : 0, //当前读取接口的进程数
  14. waitQueueTaskNum : 0 //延迟加载队列等待的任务数
  15. };
  16. function addLazyTask(task) {
  17. lazyWaitQueue.push(task);
  18. lazyLoadStatus.waitQueueTaskNum++;
  19. lazyLoadProcess();
  20. }
  21. //读取的进程数是否达到最大值
  22. function isLoadBusy(){
  23. return lazyLoadStatus.currentTaskLoadNum < options.loadTaskMaxNum ? false : true;
  24. }
  25. //触发加载器去处理队列中的任务
  26. function lazyLoadProcess(){
  27. //当加载器状态有空闲并且等待队列中有任务则处理队列中的任务
  28. while(!isLoadBusy() && lazyLoadStatus.waitQueueTaskNum > 0){
  29. lazyLoadStatus.currentTaskLoadNum++;
  30. lazyLoadStatus.waitQueueTaskNum--;
  31. var task = lazyWaitQueue.shift();
  32. lazyProcessList.push(task);
  33. getLazyLoadTaskData(task);
  34. }
  35. }
  36. //加载任务完成,从读取中列表移除,然后触发加载器运行
  37. function lazyLoadTaskDone(task){
  38. for(var i = 0; i< lazyProcessList.length; i++){
  39. if(lazyProcessList[i].id == task.id){
  40. lazyProcessList.splice(i,1);
  41. lazyLoadStatus.currentTaskLoadNum--;
  42. break;
  43. }
  44. }
  45. lazyLoadProcess();
  46. }
  47. //读取加载的接口数据并渲染页面
  48. function getLazyLoadTaskData(task){
  49. function onsuccess(data) {
  50. lazyLoadTaskDone(task);
  51. var datax = eval("(" + data + ")");
  52. if(datax["status"]=="1"){
  53. task.render(datax['data']);
  54. }
  55. }
  56. function onerrors(data) {
  57. lazyLoadTaskDone(task);
  58. }
  59. jQuery.comm.sendmessage(task.url, task.packet, onsuccess, onerrors);
  60. }
  61. //API
  62. var api = {
  63. config: function (opts) {
  64. if(!opts) return options;
  65. for(var key in opts) {
  66. options[key] = opts[key];
  67. }
  68. return this;
  69. },
  70. addTask: function (id, url, packet, render) {
  71. var task = {
  72. id: id,
  73. url: url,
  74. packet: packet,
  75. render: render
  76. };
  77. addLazyTask(task);
  78. return this;
  79. },
  80. resetQueue: function () {
  81. lazyLoadStatus.currentTaskLoadNum = 0;
  82. lazyLoadStatus.waitQueueTaskNum = 0;
  83. lazyWaitQueue = new Array();
  84. lazyProcessList = new Array();
  85. return this;
  86. }
  87. };
  88. this.lazyload = api;
  89. })();