load scripts asynchronously

前端 未结 19 1200
粉色の甜心
粉色の甜心 2020-11-22 12:01

I am using several plugins, custom widgets and some other libraries from JQuery. as a result I have several .js and .css files. I need to create a loader for my site because

19条回答
  •  遥遥无期
    2020-11-22 12:21

    Here a little ES6 function if somebody wants to use it in React for example

    import {uniqueId} from 'lodash' // optional
    /**
     * @param {String} file The path of the file you want to load.
     * @param {Function} callback (optional) The function to call when the script loads.
     * @param {String} id (optional) The unique id of the file you want to load.
     */
    export const loadAsyncScript = (file, callback, id) => {
      const d = document
      if (!id) { id = uniqueId('async_script') } // optional
      if (!d.getElementById(id)) {
        const tag = 'script'
        let newScript = d.createElement(tag)
        let firstScript = d.getElementsByTagName(tag)[0]
        newScript.id = id
        newScript.async = true
        newScript.src = file
        if (callback) {
          // IE support
          newScript.onreadystatechange = () => {
            if (newScript.readyState === 'loaded' || newScript.readyState === 'complete') {
              newScript.onreadystatechange = null
              callback(file)
            }
          }
          // Other (non-IE) browsers support
          newScript.onload = () => {
            callback(file)
          }
        }
        firstScript.parentNode.insertBefore(newScript, firstScript)
      } else {
        console.error(`The script with id ${id} is already loaded`)
      }
    }

提交回复
热议问题