You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ScriptUtil.js 2.4KB

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