tracking-loader.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { debugConsole } from '@/utils/debugging'
  2. export const createTrackingLoader = (cb: () => void, name: string) => {
  3. // avoid inserting twice
  4. let initialized = false
  5. const loadTracking = () => {
  6. // consent needed
  7. const consent = document.cookie.split('; ').some(item => item === 'oa=1')
  8. if (initialized || !consent) {
  9. return
  10. }
  11. debugConsole.log('Loading Analytics', name)
  12. initialized = true
  13. cb()
  14. }
  15. // load when idle, if supported
  16. if (typeof window.requestIdleCallback === 'function') {
  17. window.requestIdleCallback(loadTracking)
  18. } else {
  19. loadTracking()
  20. }
  21. // listen for consent
  22. window.addEventListener('cookie-consent', event => {
  23. if ((event as CustomEvent<boolean>).detail) {
  24. loadTracking()
  25. }
  26. })
  27. }
  28. export const insertScript = (attr: {
  29. src: string
  30. crossorigin?: string
  31. async?: boolean
  32. onload?: () => void
  33. }) => {
  34. const script = document.createElement('script')
  35. script.setAttribute('src', attr.src)
  36. if (attr.crossorigin) {
  37. script.setAttribute('crossorigin', attr.crossorigin)
  38. }
  39. if (attr.async) {
  40. script.setAttribute('async', 'async')
  41. }
  42. if (attr.onload) {
  43. script.onload = attr.onload
  44. }
  45. document.querySelector('head')?.append(script)
  46. }