Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/utils / src / createScriptTag.ts
Size: Mime:
/**
 * @description scoped default argument
 */
const defaultAttributes = {
  async: true,
}

function shouldIgnore(src: string): boolean {
  // no need for this in test env
  // @todo we may want to render a local import though, using a mock/
  if (process.env.NODE_ENV === 'test') {
    return true
  }
  if (typeof window !== 'object') {
    return true
  }

  // all scripts
  const scriptElements = window.document.getElementsByTagName('script')
  for (let index = 0; index < scriptElements.length; index++) {
    const script = scriptElements[index]
    // ignore it if we already loaded
    if (script.src === src) {
      // console.warn('already loaded: ', src)
      return true
    }
  }

  return false
}

interface HTMLScriptElementAttributes {
  async: boolean
  crossOrigin: string | null
  /** Sets or retrieves the status of the script. */
  defer: boolean
  integrity: string
  noModule: boolean
  /** Retrieves the URL to an external file that contains the source code or data. */
  src: string
  /** Retrieves or sets the text of the object as a string. */
  text: string
  /** Sets or retrieves the MIME type for the associated scripting engine. */
  type: string
}

/**
 * @tutorial https://hacks.mozilla.org/2009/06/defer/
 *
 * @param src url of the script tag
 * @param attributes
 * @modifies window.dom -> createElement -> <script src>
 */
function createScriptTag(
  src: string,
  attributes: Partial<HTMLScriptElementAttributes> = defaultAttributes
): void {
  if (shouldIgnore(src) === true) {
    return
  }

  const scriptElements = window.document.getElementsByTagName('script')
  // find first script
  const ref = scriptElements[0]

  // make our own new script
  const script = window.document.createElement('script')

  // set attributes
  script.src = src

  // can also object async, or enable a fn to tap this
  script.async = attributes.async

  // put before first script
  ref.parentNode!.insertBefore(script, ref)
}

export { createScriptTag }
export default createScriptTag