LoginSignup
16
19

More than 3 years have passed since last update.

Nuxt.jsでいい感じにAdobe fontsのwebフォントを読み込む

Last updated at Posted at 2019-12-09

Adobe fontsで日本語(東アジアの言語)を含むフォントを選択した場合、こんな感じのスクリプトの埋め込みを指示されると思います。

<script>
  (function(d) {
    var config = {
      kitId: '######',
      scriptTimeout: 3000,
      async: true
    },
    h=d.documentElement,t=setTimeout(function(){h.className=h.className.replace(/\bwf-loading\b/g,"")+" wf-inactive";},config.scriptTimeout),tk=d.createElement("script"),f=false,s=d.getElementsByTagName("script")[0],a;h.className+=" wf-loading";tk.src='https://use.typekit.net/'+config.kitId+'.js';tk.async=true;tk.onload=tk.onreadystatechange=function(){a=this.readyState;if(f||a&&a!="complete"&&a!="loaded")return;f=true;clearTimeout(t);try{Typekit.load(config)}catch(e){}};s.parentNode.insertBefore(tk,s)
  })(document);
</script>

これをNuxt.jsのプロジェクトへ組み込むメモです。

スクリプトの読み込み

adobeからスクリプトを読み込ませます。

nuxt.config.js
export default {
  head: {
    script: [
      { src: 'https://use.typekit.net/<PROJECT_ID>.js' }
    ]
  }
  /* 他の設定は省略 */
}

<PROJECT_ID>にAdobe Fontsで設定したWebプロジェクトのIDを入れてください。

Typekitを実行

任意の場所でTypekit.load({async: true})を実行するとフォントが読み込まれます。

layout/default.vue
<script>
export default {
  mounted() {
    Typekit.load({async: true})
  }
}
</script>

フォントの読み込みが完了する前に字形の異なる文字が表示されると都合が悪い場合は、loading周りといい感じに連携してください。

layout/default.vue
<script>
export default {
  loading: false,
  mounted() {
    this.$nextTick(() => {
      this.$nuxt.$loading.start()
      Typekit.load({
        async: true,
        active: () => {this.$nuxt.$loading.finish()}
      })
    })
  }
}
</script>
components/loading.vue
<template>
  <transition name='l'>
    <div v-if="loading" class="h-screen fixed inset-x-0 top-0 bg-white"></div>
  </transition>
</template>

<script>
export default {
  data: () => ({ loading: true }),
  methods: {
    start()  { this.loading = true  },
    finish() { this.loading = false },
  },
}
</script>

<style lang="css" scoped>
.l-enter-active { transition: all .5s ease-out }
.l-leave-active { transition: all .5s ease-out }
.l-enter, .l-leave-to { opacity: 0 }
.l-enter-to, .l-leave { opacity: 1 }
</style>

nuxt.config.js
export default = {
  loading: '@/components/loading.vue'

  /* 他の設定は省略 */
}

さいごに

scriptTimeoutの設定は無視してるんで、そこはまたいい感じに...

16
19
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
16
19