zoukankan      html  css  js  c++  java
  • vuecli3 引入script 针对没有cmd amd require等方式的js

    最近做高德开发,需要引入高德的js,但是 说实话 高德官方的文档不知道大佬们有没有看懂,反正我是没看懂,写的都什么鬼?我怎么引都引入不了,迫不得已想到了如下方法:

    一、准备一个能够在页面中插入js的方法

    export default function remoteLoad (url, hasCallback) {
        return createScript(url)
        /**
         * 创建script
         * @param url
         * @returns {Promise}
         */
        function createScript (url) {
          var scriptElement = document.createElement('script')
          document.body.appendChild(scriptElement)
          var promise = new Promise((resolve, reject) => {
            scriptElement.addEventListener('load', e => {
              removeScript(scriptElement)
              if (!hasCallback) {
                resolve(e)
              }
            }, false)
      
            scriptElement.addEventListener('error', e => {
              removeScript(scriptElement)
              reject(e)
            }, false)
      
            if (hasCallback) {
              window.____callback____ = function () {
                resolve()
                window.____callback____ = null
              }
            }
          })
      
          if (hasCallback) {
            url += '&callback=____callback____'
          }
      
          scriptElement.src = url
      
          return promise
        }
      
        /**
         * 移除script标签
         * @param scriptElement script dom
         */
        function removeScript (scriptElement) {
          document.body.removeChild(scriptElement)
        }
      }

    针对所有问题,将该文件放置于utils文件夹下

    使用方法

    目标页面:

    import remoteLoad from "@/utils/remoteLoad.js";
    async created() {
        // 已载入高德地图API,则直接初始化地图
        // console.log(this.AMap,window.AMap)
        if (window.AMap && this.AMap){
          
          this.initMap();
          // 未载入高德地图API,则先载入API再初始化
        } else {
          
          await remoteLoad(
            `https://webapi.amap.com/maps?v=1.4.10&key=${MapKey}&plugin=AMap.DistrictSearch`
          );
            await remoteLoad('https://a.amap.com/jsapi_demos/static/citys.js')
          this.initMap();
        }

    至此已经做到引入js并且初始化地图。具体想封装成组件还是直接在页面使用都是可以的,而且只加载一次,避免了反复引入的问题,感谢大佬观看

  • 相关阅读:
    Linux系统 Docker RabbitMQ容器集群部署
    Linux系统 SSH免密登入
    ubuntu server 乱码
    简单总结在github上托管工程
    在线编译系统之nodejs执行shell
    Ubuntu中软件安装与卸载
    ubuntu软件安装
    “cannot find module ‘npmlog’….”的错误
    关于事件的一点小总结
    mongodb基本操作
  • 原文地址:https://www.cnblogs.com/jinzhenzong/p/9993100.html
Copyright © 2011-2022 走看看