Dynamically loading and remove an external JavaScript or CSS file in vue
需要動態載入外部JS或CSS時,我們可以直接操作document.head 來載入新的JS/CSS與移除舊的JS/CSS。
透過document.createElement(‘link’) 我們可以創造一個外部連結,接著指定它的檔案類型參照(rel)與網址,利用appendChild()來動態載入
而在Vue中,因為沒有reload,會一直連進同一頁,會重覆動態載入到同樣的檔案,因此需要在載入前,先把同樣檔名的檔案,用remove()來刪除。
可以搭配querySelectorAll或 querySelector來匹配link的href要remove的檔案。
匹配規則如下:
[id^='https://test'] 匹配https://test為開頭的所有檔案
[id$='xxx.css'] 匹配xxx.css為結尾的所有檔案
[id*='.css'] 匹配包含.css的所有檔案
參考Function:
<template>
<div>
<button @click="appendFile">Click me to add css file</button>
</div>
</template><script>
export default {
methods : {
appendFile(){
document.querySelectorAll('link[href$="myfile.css"]').forEach(item => item.remove());
let file = document.createElement('link');
file.rel = 'stylesheet';
file.href = 'myfile.css'
document.head.appendChild(file)
}
}
}
</script>