Source: util/run_scripts_in_element.es.js

  1. /**
  2. * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
  3. *
  4. * This library is free software; you can redistribute it and/or modify it under
  5. * the terms of the GNU Lesser General Public License as published by the Free
  6. * Software Foundation; either version 2.1 of the License, or (at your option)
  7. * any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  12. * details.
  13. */
  14. function runJSFromText(text, next, appendFn) {
  15. const scriptElement = document.createElement('script');
  16. scriptElement.text = text;
  17. if (appendFn) {
  18. appendFn(scriptElement);
  19. }
  20. else {
  21. document.head.appendChild(scriptElement);
  22. }
  23. scriptElement.remove();
  24. next();
  25. }
  26. function runJSFromFile(src, next, appendFn) {
  27. const scriptElement = document.createElement('script');
  28. scriptElement.src = src;
  29. const callback = function () {
  30. scriptElement.remove();
  31. next();
  32. };
  33. scriptElement.addEventListener('load', callback, {once: true});
  34. scriptElement.addEventListener('error', callback, {once: true});
  35. if (appendFn) {
  36. appendFn(scriptElement);
  37. }
  38. else {
  39. document.head.appendChild(scriptElement);
  40. }
  41. }
  42. function runScriptsInOrder(scripts, i, defaultFn, appendFn) {
  43. const scriptElement = scripts[i];
  44. const runNextScript = () => {
  45. if (i < scripts.length - 1) {
  46. runScriptsInOrder(scripts, i + 1, defaultFn, appendFn);
  47. }
  48. else if (defaultFn) {
  49. setTimeout(defaultFn);
  50. }
  51. };
  52. if (!scriptElement) {
  53. return;
  54. }
  55. else if (scriptElement.type && scriptElement.type !== 'text/javascript') {
  56. runNextScript();
  57. }
  58. else {
  59. scriptElement.remove();
  60. if (scriptElement.src) {
  61. runJSFromFile(scriptElement.src, runNextScript, appendFn);
  62. }
  63. else {
  64. runJSFromText(scriptElement.text, runNextScript, appendFn);
  65. }
  66. }
  67. }
  68. export default function (element, defaultFn, appendFn) {
  69. const scripts = element.querySelectorAll('script');
  70. if (!scripts.length && defaultFn) {
  71. setTimeout(defaultFn);
  72. return;
  73. }
  74. runScriptsInOrder(scripts, 0, defaultFn, appendFn);
  75. }