LoginSignup
1
2

More than 3 years have passed since last update.

複数のファイルを並行に取得して読込速度を改善する

Posted at

はじめに

<link rel="preload"> を使用することでブラウザに対して早期にファイル取得を促し、読込時間を短縮させることができます。

preload

preloadは、ブラウザのレンダリング機構が起動するよりも早く、ファイルの読込を開始させたい場合に使用します。

改善前

開発者ツールのNetworkからファイルを読み込むタイミングを確認します。

image52.png

cssファイルが取得&読み込まれた後に画像(webp)、Googleフォント(font)が取得されていることがわかります。
画像とフォントをcssファイルやjsファイルなどと並行して読み込むことができれば、ページの読込速度の改善が見込めそうです。

実装を見ると背景画像とフォントはcssファイルの中で読み込んでいます。

index.html
<link rel="stylesheet" href="./main.css">
main.css
@import url(https://fonts.googleapis.com/css?family=Roboto:900|Roboto+Mono:300,400,700); // Googleフォントの読込
background-image-container {
  background-size:cover;
  background-repeat:no-repeat;
  background-position:top;
  background-image: url('./assets/images/space.webp') // 背景画像の読込
}

この場合、背景画像とフォントはcssファイルが完全にダウンロードされた後、上から順にcssが解析されていく途中で取得されることになります。

改善後

では、背景画像とフォントを並行して読み込ませるために、headタグ内に <link rel="preload"> を実装します。

index.html
<link rel="preload" href="./assets/images/space.webp" as="image">
<link rel="preload" href="https://fonts.gstatic.com/robotomono.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:900|Roboto+Mono:300,400,700">
<link rel="stylesheet" href="./main.css">

image51.png

cssファイルとwebp、font の読込が並列になっていることがわかります。

結果、背景画像をいち早く画面に表示させ、文字にもいち早くフォントを当てることができます。

注意点

1つ注意点としては、オリジンを跨いでファイルを取得する場合は
crossorigin 属性を付与しておく必要があります。

通常、Webサーバには同一オリジンポリシーがあり、オリジンを跨いだアクセスは制限がかかります。
crossorigin 属性はオリジンを跨いだアクセスを許可する際に付与します。

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