LoginSignup
6
2

More than 5 years have passed since last update.

htmlで各ページに入るヘッダなどの部品を共通化する

Last updated at Posted at 2018-11-04

jQueryのload()を使う

  • index.htmlと同じ階層にincludeディレクトリを作成し、その中に共通化するヘッダをheader.htmlとして作成
  • index.htmlの<head>内に読み込み処理を書く
  • 対象はクラスで指定する

index.html

<head>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        $(".load_header").load("include/header.html");
    });
    </script>

</head>

<body>
    <header class="load_header">

    </header>

</body>

確認する

Chromeだと次のエラーが発生し表示されない

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

macOS(High Sierra)の場合は下記のように起動すると表示できた
sudo /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files

参考

共通部分をパーツ化させる
https://style01.net/399/

[その他] ChromeにてAjaxでローカルファイルにアクセス
https://qiita.com/cigalecigales/items/33afaa42f91542ffa62e

Chrome上でAjaxを使ってローカルファイルにアクセスする方法
https://qiita.com/takahiro_itazuri/items/c2807b7a7d9d9537cffb

6
2
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
6
2