Webブラウザ上で動く JavaScript の話。

RequireJStext.js プラグインを使ってテキストファイル (というかHTMLファイルの断片) を取得して表示してみるサンプル。

Load text files and treat them as dependencies. Great for loading templates. The text strings can be inlined in an optimized build when the optimizer is used.

Download RequireJS

ファイル構成。


├── hoge.html
├── index.html
├── libs
│   └── text.js
├── main.js
└── require.js

index.html

RequireJS を使って main.js を読み込む。


<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>RequireJS: sample</title>
  <!-- data-main attribute tells require.js to load
       scripts/main.js after require.js loads. -->
  <script data-main="main" src="require.js"></script>
</head>
<body>
<h1>RequireJS: sample</h2>
<div id="hoge"></div>
</body>
</html>

main.js

RequireJS の公式サイト Download RequireJS からダウンロードした text.js プラグインのパスを指定。

「text!」で指定した hoge.html ファイルを読み込んで、 index.html の中に埋め込む。


require.config({
  paths: {
    'text': 'libs/text'
  }
});

require(
  ['text!hoge.html'],
  function(hogeHtml) {

  document.getElementById('hoge').innerHTML = hogeHtml;
  console.log(hogeHtml);
});

hoge.html

読み込むテキストファイル。


<p>hoge</p>
<p>foo</p>
<p>bar</p>

RequireJS の text.js プラグインは XMLHttpRequest でファイルを取得しているので、テキストファイルを取得する際には HTTP 通信が発生している。たくさんのファイルを読み込むと処理に時間がかかるかもしれないので注意。

text.js プラグインを使えば、テンプレートになるHTMLファイルを読み込んで JavaScript 側で値を埋め込むなどの使い方ができそう。

サンプルコードはこちら ⇒ RequireJS: sample

tags: javascript

Posted by NI-Lab. (@nilab)