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.3KB

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