๋ฐ์ํ
| ๋ฌธ์ ์ํฉ
index.html๊ณผ sub/subpage.html ์ ๊ฐ์ JS๋ฅผ ๊ณต์ ํด์ ์ฌ์ฉํ๋ ์ํฉ.
๊ฐ์ mp3ํ์ผ์ JS๋ฅผ ํตํด ๊ฐ์ ธ์์ผ ํ๋๋ฐ,
๊ฒฝ๋ก๊ฐ ๋ฌ๋ผ์ JS๊ฐ sub/subpage.html ์์ ๋์ํ ๊ฒฝ์ฐ'. ./ '๊ฐ ์ถ๊ฐ๋์ด์ผ ํจ
$(document).ready(function () {
const basePath = window.location.pathname.includes('/sub/') ? '../' : '';
const audioPaths = {
Bgm1_Fireplace: basePath + 'bgm/DC_fire.mp3',
Bgm2_Rain: basePath + 'bgm/DC_rain.mp3',
Bgm3_MxRedKeyboard: basePath + 'bgm/DC_hesper_Key_asmr.mp3',
};
}
[๋ฐฉ๋ฒ]
1. basePath ๊ณ์ฐ: window.location.pathname.includes('/sub/')๋ฅผ ํตํด ํ์ฌ ๊ฒฝ๋ก๊ฐ sub ํด๋ ์์ ์๋์ง ํ์ธํฉ๋๋ค.
๋ง์ฝ sub ํด๋ ์์ ์๋ค๋ฉด, basePath๋ '../'๋ก ์ค์ ๋๊ณ , ๊ทธ๋ ์ง ์์ผ๋ฉด ๋น ๋ฌธ์์ด('')๋ก ์ค์ ๋ฉ๋๋ค.
2. audioPaths์ ๊ฒฝ๋ก ์์ : ๊ฐ ๊ฒฝ๋ก์ basePath๋ฅผ ์ถ๊ฐํ์ฌ, ํ์ฌ ๊ฒฝ๋ก์ ๋ฐ๋ผ ์ฌ๋ฐ๋ฅธ ํ์ผ ๊ฒฝ๋ก๊ฐ ์ค์ ๋๋๋ก ํฉ๋๋ค.
์ด๋ ๊ฒ ํ๋ฉด, index.html์์๋ sub ํด๋ ๋ด์ HTML ํ์ผ์์ ๋ชจ๋ ๊ณตํต์ ์ธ JavaScript ํ์ผ์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
[์์ธํ ์ค๋ช ]
1. window.location.pathname:ํ์ฌ ์น ํ์ด์ง์ URL ๊ฒฝ๋ก๋ฅผ ๋ฐํํฉ๋๋ค.์๋ฅผ ๋ค์ด, ์น ํ์ด์ง๊ฐ https://example.com/sub/page.html์ ์๋ค๋ฉด, window.location.pathname์ '/sub/page.html'์ ๋ฐํํฉ๋๋ค.
๋ง์ฝ ํ์ด์ง๊ฐ https://example.com/index.html์ ์๋ค๋ฉด, window.location.pathname์ '/index.html'์ ๋ฐํํฉ๋๋ค.
2.includes('/sub/'):์ด ๋ฉ์๋๋ window.location.pathname์์ ํน์ ๋ฌธ์์ด('/sub/')์ด ํฌํจ๋์ด ์๋์ง๋ฅผ ํ์ธํฉ๋๋ค.์๋ฅผ ๋ค์ด, ๊ฒฝ๋ก๊ฐ '/sub/page.html'์ด๋ฉด includes('/sub/')๋ true๋ฅผ ๋ฐํํฉ๋๋ค.๋ฐ๋ฉด์ ๊ฒฝ๋ก๊ฐ '/index.html'์ด๋ฉด includes('/sub/')๋ false๋ฅผ ๋ฐํํฉ๋๋ค.
3.์ผํญ ์ฐ์ฐ์ (? :):์ด ์ฐ์ฐ์๋ ์กฐ๊ฑด ? ์ฐธ์ผ ๋์ ๊ฐ : ๊ฑฐ์ง์ผ ๋์ ๊ฐ์ ํ์์ผ๋ก ์ฌ์ฉ๋ฉ๋๋ค.์ด ๊ฒฝ์ฐ, window.location.pathname.includes('/sub/')๊ฐ true์ด๋ฉด '../'๋ฅผ ๋ฐํํ๊ณ , false์ด๋ฉด ''(๋น ๋ฌธ์์ด)์ ๋ฐํํฉ๋๋ค.
4. '../' ๋๋ '':../: ์์ ๋๋ ํ ๋ฆฌ๋ฅผ ๋ํ๋ ๋๋ค. ์๋ฅผ ๋ค์ด, sub ํด๋ ๋ด์ HTML ํ์ผ์์ /bgm/DC_fire.mp3๋ฅผ ์ฐธ์กฐํ๋ ค๋ฉด ์๋ ๊ฒฝ๋ก๋ก ../bgm/DC_fire.mp3๋ฅผ ์ฌ์ฉํด์ผ ํฉ๋๋ค.'': ๋น ๋ฌธ์์ด๋ก, ํ์ฌ ๋๋ ํ ๋ฆฌ์์ ํ์ผ์ ์ฐธ์กฐํ ๋ ์ฌ์ฉ๋ฉ๋๋ค. ์๋ฅผ ๋ค์ด, index.html๊ณผ ๊ฐ์ ์ต์์ ๋๋ ํ ๋ฆฌ์์ bgm/DC_fire.mp3 ํ์ผ์ ์ฐธ์กฐํ ๋๋ ๊ฒฝ๋ก๋ฅผ ๋ณ๊ฒฝํ ํ์๊ฐ ์์ต๋๋ค.
์์ ๊ฐ์ด
๊ฒฝ๋ก์ฃผ์๊ฐ '/sub'๋ฅผ ๊ฐ์ง๊ณ ์์ผ๋ฉด (.includes) (์ผํญ์ฐ์ฐ์ ์ฌ์ฉํ์ฌ ํ๋ณ ? ์ฐธ์ด๋ฉด'../' ์ถ๊ฐ : ์๋๋ฉด ๋น๋ฌธ์์ด' ' ์ถ๊ฐ
์ฆ, basePath๋ฅผ ์ถ๊ฐํ์ฌ bgm paths๋ฅผ ๊ฐ์ ธ์ค๋๋ก ๋์ ์ผ๋ก ์ถ๊ฐํ ์ ์์!

๋ฐ์ํ