LoginSignup
7
3

More than 1 year has passed since last update.

外部のJSファイルを読み込む方法

Last updated at Posted at 2022-03-15

外部のJavaScriptファイルを読み込む方法をまとめます。

以下、

index.js→呼び出すファイル

import.js→呼び出されるファイル

とします。

import/export

import/exportを使う方法です。

まず呼び出されるファイルにて、渡したい値にexportを設定します。

import.js
export const nameText = `太郎`;

複数の値を渡す場合などは、最後にまとめて設定することもできます。

import.js
const nameText = `太郎`;

const genderText = `男`;

export { nameText, genderText };

続いて呼び出すファイルにて、importを設定します。

index.js
// 読み込みたい値を設定する
import { nameText } from './import.js';

const testElement = document.getElementById('test');

// 外部ファイルの値を使用できる
testElement.innerHTML = `こんにちは${nameText}さん`;

scriptタグにtype="module"を設定することでimport/exportが機能します。

index.html
<head>
  <script type="module" src="./index.js"></script>
</head>
<body>
  <p id="test"></p>
</body>

scriptタグ(静的)

続いてscriptタグを用いた方法です。

index.html
<script src="./import.js"></script>
<script src="./index.js"></script>

HTMLのscriptタグで読み込まれたJavaScriptファイルは全てがスコープの範囲となるため、外部のJavaScriptファイルにもアクセスできるようになります。

注意点はファイルの読み込み順です。

今回の場合、import.jsを後に読み込んでしまうとエラーになります。

index.jsを実行した時点で、import.js内の値はまだ定義されていないためです。

scriptタグの記述順やdefer属性を付与するなどして、依存関係に注意します。

※defer属性についてはこちら→scriptタグの書き方【同期的読み込みと非同期的読み込み】

scriptタグ(動的)

scriptタグはJavaScriptファイル内で作成、設定することもできます。

index.js
// scriptタグを作成
const scriptElement = document.createElement('script');
// 読み込みたい外部ファイルを設定
scriptElement.src = "./import.js";
// bodyタグ内に設置
document.body.appendChild(scriptElement);

こちらも依存関係に注意しましょう。

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