jquery.frameready.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * @param {function} callback
  3. * @param {string} target
  4. * @param {Array} resources
  5. * @constructor
  6. */
  7. $.frameReady = function (callback, targetSelector, resources) {
  8. /**
  9. * @type {window}
  10. */
  11. var targetWindow = document.querySelector(targetSelector);
  12. /**
  13. * @type {Document}
  14. */
  15. var targetDocument = null;
  16. var scripts = resources.filter(function (resource) {
  17. return resource.type === 'script';
  18. });
  19. var stylesheets = resources.filter(function (resource) {
  20. return resource.type === 'stylesheet';
  21. });
  22. var scriptsCount = (function () {
  23. var count = 0;
  24. /**
  25. * @param {Object} parentScript
  26. */
  27. function countScripts(parentScript) {
  28. count++;
  29. if (!parentScript.hasOwnProperty('deps')) {
  30. return;
  31. }
  32. parentScript.deps.forEach(countScripts);
  33. }
  34. scripts.forEach(countScripts);
  35. return count;
  36. })();
  37. var scripsLoadedCount = 0;
  38. targetWindow.onload = function () {
  39. scripsLoadedCount = 0;
  40. targetDocument = targetWindow.contentDocument;
  41. scripts.forEach(function (script) {
  42. createScript(script);
  43. });
  44. stylesheets.forEach(function (stylesheet) {
  45. createStylesheet(stylesheet);
  46. });
  47. };
  48. /**
  49. * @param {Object} script
  50. */
  51. function createScript(script) {
  52. /**
  53. * @type {HTMLScriptElement}
  54. */
  55. var elParent = targetWindow.contentDocument.createElement('script');
  56. elParent.async = false;
  57. elParent.onload = function () {
  58. scripsLoadedCount++;
  59. if (!script.hasOwnProperty('deps')) {
  60. tryExecuteCallback();
  61. return;
  62. }
  63. script.deps.forEach(function (scriptB) {
  64. createScript(scriptB);
  65. });
  66. };
  67. elParent.setAttribute('src', script.src);
  68. targetDocument.body.appendChild(elParent);
  69. }
  70. /**
  71. * @param {Object} stylesheet
  72. */
  73. function createStylesheet(stylesheet) {
  74. /**
  75. * @type {HTMLLinkElement}
  76. */
  77. var el = targetWindow.contentDocument.createElement('link');
  78. el.setAttribute('href', stylesheet.src);
  79. el.setAttribute('rel', "stylesheet");
  80. el.setAttribute('type', "text/css");
  81. if (targetDocument.head) {
  82. targetDocument.head.appendChild(el);
  83. }
  84. }
  85. function tryExecuteCallback() {
  86. if (scripsLoadedCount < scriptsCount) {
  87. return;
  88. }
  89. targetWindow.contentWindow.eval('(' + callback.toString() + ')();');
  90. }
  91. };