在javascript中动态加载leaflet.js

时间:2019-07-15 04:34:12

标签: javascript leaflet

我需要在javascript中动态加载leaflet.js和leaflet.css文件。因此,我正在动态创建脚本和链接标签,并将它们附加到文档的开头,并使用脚本的onload函数初始化地图。

但是我收到错误消息“未定义L”


    var leafletScript = document.createElement("script");
    leafletScript.id = "leafletScript"
    leafletScript.type = "text/javascript";
    leafletScript.src = "https://unpkg.com/leaflet@1.5.1/dist/leaflet.js";
    document.getElementsByTagName('head')[0].appendChild(leafletScript);

    var leafletCSS = document.createElement("link");
    leafletCSS.id = "leafletCSS"
    leafletCSS.setAttribute('rel', 'stylesheet');
    leafletCSS.setAttribute('type', 'text/css');
    leafletCSS.setAttribute('href', 
        'https://unpkg.com/leaflet@1.5.1/dist/leaflet.css');
    document.getElementsByTagName('head')[0].appendChild(leafletCSS);

    leafletScript.onload = function(){
        console.log(L);
    }

0 个答案:

没有答案