使用 Vue 動態載入 JS 檔案
寫過前端的都知道,最麻煩的就是更新 JS 檔後,使用者在網頁上用的還是舊版本,有一個解決辦法是在 JS 網址後面加一串數字,這樣就可強迫更新。另一個我最近學到的是這些靜態檔理應佈在 CDN,這樣才能減輕伺服器負擔以及加快檔案載入。
但這些都有共同缺點,就是檔案位址必須在後端產生,對前後端分離來說相當不方便,所以筆者找到了一篇可參考的文章,在這跟大家分享。
以下用 TypeScript 示範:
import { defineComponent, createApp } from 'vue';
let v = defineComponent({
name: "app",
data() {
return {
x: "aaa3",
y: "aaa4"
};
},
mounted: function () {
let divScripts = document.getElementById("dynamicScript");
let newScript = document.createElement('script');
//網址可透過 Web API 取得
newScript.src = 'https://cse.google.com/cse.js?cx=007968012720720263530:10z7awj2l37';
divScripts.appendChild(newScript);
}
});
export function GetVueObject(divName: string): any {
return createApp(v).mount(divName);
}
再來是前端的呼叫
<script type="module" src="~/js/app.js"></script>
<script type="module">
import { GetVueObject} from "./js/app.js";
var vueApp = GetVueObject("#app");
</script>
}
<div id="dynamicScript">
</div>
參考資料