LoginSignup
1
1

More than 1 year has passed since last update.

scriptタグを使いまわしたい

Last updated at Posted at 2021-08-10

どういうことか

いろんなHTMLに同じscriptタグ(js,css)を使いたい...!
ググっても出てこない...そんなあなたにお勧めです!
初投稿です。

沼ってたとき

Document.write 非推奨
innerHTML 使えない
insertAdjacentHTML 使えない

なぜ

セキュリティの関係で無効化されてるようです。

解決策

createElementを使いましょう!
コードを書いてみました。

head.js
var script;
var link;
const js = url => {
    script = document.createElement('script');
    script.src = url;
    document.head.appendChild(script);
}
const css = url => {
    link = document.createElement('link');
    script.href = url;
    script.rel = "stylesheet";
    document.head.appendChild(script);
}
//使用例
js("hoge.js");
js("https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.js")
css("hoge.css");
css("https://fonts.googleapis.com/css?family=M+PLUS+Rounded+1c");
index.html
<head>
  <script src="head.js"></script>
</head>

相対パスも使えて便利です!
使えなかったらごめんなさい😥

1
1
5

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
1
1