Skip to content

Commit

Permalink
fix: use script to load fonts
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardogobbosouza committed Oct 21, 2020
1 parent 482fdda commit 0a453c1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
21 changes: 14 additions & 7 deletions lib/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,17 +107,24 @@ module.exports = function (moduleOptions) {
})
}

// import CSS
this.options.head.style = this.options.head.style || []
this.options.head.style.push({
hid: 'gf-style',
pbody: true,
innerHTML: `@import "${url}"`
// append CSS
this.options.head.script = this.options.head.script || []
this.options.head.script.push({
hid: 'gf-script',
innerHTML: `(function(){var l=document.createElement('link');l.rel="stylesheet";l.href="${url}";document.querySelector("head").appendChild(l);})();`
})

// no-JS fallback
this.options.head.noscript = this.options.head.noscript || []
this.options.head.noscript.push({
hid: 'gf-noscript',
innerHTML: `<link rel="stylesheet" href="${url}">`
})

// Disable sanitazions
this.options.head.__dangerouslyDisableSanitizersByTagID = this.options.head.__dangerouslyDisableSanitizersByTagID || {}
this.options.head.__dangerouslyDisableSanitizersByTagID['gf-style'] = ['innerHTML']
this.options.head.__dangerouslyDisableSanitizersByTagID['gf-script'] = ['innerHTML']
this.options.head.__dangerouslyDisableSanitizersByTagID['gf-noscript'] = ['innerHTML']
})
}

Expand Down
21 changes: 19 additions & 2 deletions test/basic.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,28 @@ describe('basic', () => {
await nuxt.close()
})

test('render', async () => {
test('has prefetch link', async () => {
const html = await get('/')
expect(html).toContain('<link data-n-head="ssr" data-hid="gf-prefetch" rel="dns-prefetch" href="https://fonts.gstatic.com/">')
})

test('has preconnect link', async () => {
const html = await get('/')
expect(html).toContain('<link data-n-head="ssr" data-hid="gf-preconnect" rel="preconnect" href="https://fonts.gstatic.com/" crossorigin="true">')
})

test('has preload link', async () => {
const html = await get('/')
expect(html).toContain('<link data-n-head="ssr" data-hid="gf-preload" rel="preload" as="style" href="https://fonts.googleapis.com/css2?family=Roboto&amp;family=Lato">')
expect(html).toContain('<style data-n-head="ssr" data-hid="gf-style" data-pbody="true">@import "https://fonts.googleapis.com/css2?family=Roboto&family=Lato"</style>')
})

test('has script to import font css', async () => {
const html = await get('/')
expect(html).toContain('data-hid="gf-script"')
})

test('has noscript fallback', async () => {
const html = await get('/')
expect(html).toContain('data-hid="gf-noscript"')
})
})

0 comments on commit 0a453c1

Please sign in to comment.