loader.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Loads a JavaScript file from the given URL and executes it.
  3. *
  4. * @param {string} url Address of the .js file to load
  5. * @param {function} callback Method to invoke when the script
  6. * has loaded and executed
  7. */
  8. export const loadScript = (url: string, callback?: (error?: Error) => void) => {
  9. const script = document.createElement('script');
  10. script.type = 'text/javascript';
  11. script.async = false;
  12. script.defer = false;
  13. script.src = url;
  14. if (typeof callback === 'function') {
  15. // Success callback
  16. script.onload = (event: Event) => {
  17. if (event.type === 'load') {
  18. // Kill event listeners
  19. script.onload = script.onerror = null;
  20. callback();
  21. }
  22. };
  23. // Error callback
  24. script.onerror = (err: Event | string) => {
  25. // Kill event listeners
  26. script.onload = script.onerror = null;
  27. callback(new Error('Failed loading script: ' + script.src + '\n' + err));
  28. };
  29. }
  30. // Append the script at the end of <head>
  31. const head = document.querySelector('head');
  32. if (head) {
  33. head.insertBefore(script, head.lastChild);
  34. }
  35. };