
script๋ฅผ ์คํํ๊ณ ์ถ์ ์ด๋ฆ์ ๋ฐฐ์ด์ ์ ์ผ๋ฉด, ๋ฒํผ์ด ์์ฑ๋๋ฉฐ, ๋๋ฅด๋ฉด ํด๋น jsํ์ผ์ด ์คํ๋๋ค.
index.html์์ scriptํ์ผ์ ์๋์ผ๋ก ์ผ์ผ์ด ๋ฐ๊ฟ์ผํ๋ ์๊ณ ๋ฅผ ๋์๋ค.
const fileList = ['class', 'promise']
const hasScript = (fileName) => {
const currentScripts = document.head.getElementsByTagName('script')
for(scriptElem of currentScripts){
if(scriptElem.src.includes(fileName)){
return true
}
}
return false
}
const removeScript = (fileName) => {
const currentScripts = document.head.getElementsByTagName('script')
for(scriptElem of currentScripts){
if(scriptElem.src.includes(fileName)){
scriptElem.remove()
console.log(`Success to delete ${fileName}`)
}
}
}
const addScript = (fileName) => {
const script = document.createElement('script')
script.setAttribute('src', `/${fileName}.js`)
document.querySelector('head').appendChild(script)
console.log(`Success to append ${fileName}`)
}
const createButton = (fileName) => {
const buttonElem = document.createElement('button')
buttonElem.textContent = fileName
buttonElem.addEventListener('click', () => {
hasScript(fileName)
? removeScript(fileName)
: addScript(fileName)
})
return buttonElem;
}
const init = () => {
fileList.forEach((fileName)=>{
const buttonElem = createButton(fileName)
document.querySelector('body').append(buttonElem)
})
}
init()
๋ฐ์ํ
'๐ Front > ๐ฑ Vanilla JS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| ํ๋กํ ํ์ : ์๋ฐ์คํฌ๋ฆฝํธ์ ํต์ฌ ์ฒ ํ (์ ๋ฆฌ) (0) | 2022.01.11 |
|---|---|
| ๋ถ๋ณ๊ฐ๊ณผ ๊ฐ๋ณ๊ฐ์ ๋๋๋ ๊ธฐ์ค์ ๋ญ๊น? (0) | 2022.01.07 |
| [Iterable VS Enumerable] ๊น๋ํ๊ฒ ์ ๋ฆฌํ๊ณ ๊ฐ์๋ค (0) | 2021.11.19 |
| arguments ๊ฐ์ฒด: function์์ ์๋ ๋, ๋๊ฐ ์ ์ธํ๋? (0) | 2021.11.18 |
| [addEventListener] ์ฝ๋ฐฑํจ์์๊ฒ ์ธ์๋ฅผ ์ฃผ๋ ๋ฐฉ๋ฒ (0) | 2021.11.17 |