Reputation: 2598
I created and deployed a Nuxt project, and Google Pagespeed points out (rightfully) that my fonts are not preloaded when displaying the page, which hurts my PageSpeed score a lot.
I already checked this question: nuxt.js - preload .woff fonts loaded as @font-face and also this issue: https://github.com/nuxt/nuxt.js/issues/1508, but I could not fix the problem. Here is what I tried...
Currently my fonts are loaded in assets/scss/_text.scss
:
@font-face {
font-family: Raleway-Medium;
src: url("~assets/fonts/Raleway/Raleway-Medium.woff2");
}
// ...
Then in assets/scss/main.scss
:
@import '~assets/scss/_text.scss';
// ...
And finally in nuxt.config.js
:
export default {
// ...
css: ['@/assets/scss/main.scss'],
// ...
render: {
bundleRenderer: {
shouldPreload: (_file, type) => {
console.log(_file, type)
return ['script', 'style', 'font'].includes(type)
}
}
},
}
Unfortunately, my fonts are not preloaded at all. Actually, the console.log
I added in the bundleRenderer
function does not even find any font or style file, here is what is logged:
runtime.js script
commons.app.js script
vendors.app.js script
app.js script
Does anyone know how I can fix this? Thanks a lot!
Upvotes: 2
Views: 1735
Reputation: 2934
Actually, I'm using a workaround, but I'm pretty sure it's not a perfect solution.
I wrote a node script (post-build.js) that I run after the "generate" command.
I use cheerio to modifiy html file content
const fs = require('fs')
const cheerio = require('cheerio')
const links = []
fs.readdirSync('./dist/_nuxt/fonts/').forEach((file) => {
const fileExtension = file.split('.')[1]
if (fileExtension === 'woff2') {
links.push(
`<link rel="preload" href="/_nuxt/fonts/${file}" as="font" type="font/woff2" crossorigin>`
)
}
})
const html = fs.readFileSync('./dist/index.html', 'utf8')
const $ = cheerio.load(html)
$('head').append(links.join(' '))
fs.writeFileSync(`./dist/index.html`, $.html(), 'utf8', () => {})
So then i add following lin in my scripts of my package.json file
"scripts:{
"generate": "nuxt generate && node ./npm-scripts/post-build.js"
}
Upvotes: 1
Reputation: 2598
If anybody is having the same problem: font preloading is only active in universal mode, and does not activate in dev mode.
Changing to universal mode and running npm run generate
creates pages in dist/
with the fonts preloaded.
Upvotes: 0