Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ScriptUtil.ts 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import currentExecutingScript from 'current-executing-script';
  2. /* eslint-disable max-params */
  3. export interface ILoadScriptOptions {
  4. async: boolean;
  5. errorCallback?: () => void;
  6. loadCallback?: () => void;
  7. prepend: boolean;
  8. relativeURL: boolean;
  9. src: string;
  10. }
  11. /**
  12. * Implements utility functions which facilitate the dealing with scripts such
  13. * as the download and execution of a JavaScript file.
  14. */
  15. const ScriptUtil = {
  16. /**
  17. * Loads a script from a specific source.
  18. *
  19. * @param src the source from the which the script is to be (down)loaded
  20. * @param async true to asynchronously load the script or false to
  21. * synchronously load the script
  22. * @param prepend true to schedule the loading of the script as soon as
  23. * possible or false to schedule the loading of the script at the end of the
  24. * scripts known at the time
  25. * @param relativeURL whether we need load the library from url relative
  26. * to the url that lib-jitsi-meet was loaded. Useful when sourcing the
  27. * library from different location than the app that is using it
  28. * @param loadCallback on load callback function
  29. * @param errorCallback callback to be called on error loading the script
  30. */
  31. loadScript({
  32. src,
  33. async,
  34. prepend,
  35. relativeURL,
  36. loadCallback,
  37. errorCallback
  38. }: ILoadScriptOptions): void {
  39. const d = document;
  40. const tagName = 'script';
  41. const script = d.createElement(tagName);
  42. const referenceNode = d.getElementsByTagName(tagName)[0];
  43. script.async = async;
  44. if (relativeURL) {
  45. // finds the src url of the current loaded script
  46. // and use it as base of the src supplied argument
  47. const scriptEl = currentExecutingScript();
  48. if (scriptEl) {
  49. const scriptSrc = scriptEl.src;
  50. const baseScriptSrc
  51. = scriptSrc.substring(0, scriptSrc.lastIndexOf('/') + 1);
  52. if (scriptSrc && baseScriptSrc) {
  53. // eslint-disable-next-line no-param-reassign
  54. src = baseScriptSrc + src;
  55. }
  56. }
  57. }
  58. if (loadCallback) {
  59. script.onload = loadCallback;
  60. }
  61. if (errorCallback) {
  62. script.onerror = errorCallback;
  63. }
  64. script.src = src;
  65. if (prepend) {
  66. referenceNode.parentNode.insertBefore(script, referenceNode);
  67. } else {
  68. referenceNode.parentNode.appendChild(script);
  69. }
  70. }
  71. };
  72. /* eslint-enable max-params */
  73. export default ScriptUtil;