0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでハッシュの変更に応じて外部jsファイルを動的に読み込む

Posted at

ハッシュが変わると、そのハッシュ名のjsファイルを読み込む。
サーバ側を作りたくなくて、最初にすべてのjsファイルを読み込みたくない場合に利用できるはず。

<!DOCTYPE html>
<html>
<head></head>
<body>
<a href="#test">test</a>
<script>
window.addEventListener('hashchange', () => {
  const hash = window.location.hash,
        src = "./" + hash.slice(1) + ".js";
  loadScript(src);
});

function loadScript(src) {
  const script = document.createElement('script');
  script.onload = () => {
    console.log(`"${src}" has loaded.`);
  };
  script.src = src;
  document.body.appendChild(script);
}
</script>
</body>
</html>
test.js
console.log('"./test.js" is being loaded.');
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?