如果是在頁面直接透過script標籤引入mapapi.js是沒什麼大問題的!!
不過由於要實作讓使用者切換線上與離線地圖就發現了很扯的bug,
var jsTag = '<' + 'script src="http://localhost:8080/js/libs/offlinemap/google/mapapi.js"' + ' type="text/javascript"><' + '/script>'; document.write(jsTag);
使用document.createElement的方法,console會噴以下這個錯誤
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
var element = document.createElement("script"); element.src = "js/libs/offlinemap/google/mapapi.js"; element.type = "text/javascript"; document.getElementsByTagName("head")[0].appendChild(element);
成功的方法
最後參考到這篇的解法,重新覆寫document.write方法就可以正常載入了http://stackoverflow.com/questions/3125049/cannot-add-google-map-api-script-after-pageloadfunction writeGoogleMapsScript() { document.oldWrite = document.write; document.write = function (text) { console.log('new document write'); var parser = new DOMParser(); var element = parser.parseFromString(text, "text/xml"); var child = element.firstChild; var element = document.createElement("script"); element.src = child.getAttribute('src'); element.type = "text/javascript"; document.getElementsByTagName("head")[0].appendChild(element); document.write = document.oldWrite; }; var element = document.createElement("script"); element.src = "js/libs/offlinemap/google/mapapi.js"; element.type = "text/javascript"; document.getElementsByTagName("head")[0].appendChild(element); }
沒有留言:
張貼留言
留個話吧:)