美文网首页
js文件缓存加载

js文件缓存加载

作者: River_mx | 来源:发表于2018-11-26 16:46 被阅读0次
 <script>
      (function () {
        const getScriptsUrl = () => {
          let scriptHtml = document.head.querySelector('noscript').innerHTML.match(/"([^>]*)"/g)
          scriptHtml = scriptHtml.map(js => js.replace(/\"/g, ""))
          return scriptHtml
        }

        const requestScript = (scriptUrl) => {
          const httpRequest = new XMLHttpRequest()
          httpRequest.onreadystatechange = () => {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200 || httpRequest.status === 304) {
              const assetsScript = document.createElement('script')
              assetsScript.defer = true
              assetsScript.innerHTML = httpRequest.responseText
              document.head.appendChild(assetsScript)

              window.localStorage.setItem(scriptUrl + '_' + window.PEAPP.assetsVersion, encodeURIComponent(httpRequest.responseText))
            }
          }
          httpRequest.open('GET', window.PEAPP.assetsPath + scriptUrl + '?_v=' + window.PEAPP.assetsVersion, true)
          httpRequest.send(null)
        }

        const renderScript = () => {
          const loadScripts = getScriptsUrl()
          for (let i = 0; i < loadScripts.length; i++) {
            if (!window.localStorage.getItem(loadScripts[i] + '_' + window.PEAPP.assetsVersion)) {
              requestScript(loadScripts[i])
            } else {
              const assetsScript = document.createElement('script')
              assetsScript.defer = true
              assetsScript.innerHTML = decodeURIComponent(window.localStorage.getItem(loadScripts[i] + '_' + window.PEAPP.assetsVersion))
              setTimeout(() => {
                document.head.appendChild(assetsScript)
              }, 0)
            }
          }
        }

        return {
          init() {
            renderScript()
          }
        }
      })().init()
  </script>

相关文章

网友评论

      本文标题:js文件缓存加载

      本文链接:https://www.haomeiwen.com/subject/clgbqqtx.html