Nuxt/lib/core/meta.js

75 lines
2.0 KiB
JavaScript
Raw Normal View History

2017-08-18 16:05:01 +00:00
import { attrsStr } from 'utils'
import LRU from 'lru-cache'
export default class MetaRenderer {
constructor (nuxt, renderer) {
2017-08-18 16:05:01 +00:00
this.nuxt = nuxt
this.renderer = renderer
2017-08-18 16:05:01 +00:00
this.options = nuxt.options
this.cache = LRU({})
}
render ({ url = '/' }) {
let head = this.cache.get(url)
if (head) {
return head
}
head = ''
// Title
if (typeof this.options.head.title === 'string') {
head += `<title data-n-head="true">${this.options.head.title || ''}</title>`
}
// Meta
if (Array.isArray(this.options.head.meta)) {
this.options.head.meta.forEach(meta => {
2017-08-19 08:46:58 +00:00
head += `<meta data-n-head="true" ${attrsStr(meta)}/>`
2017-08-18 16:05:01 +00:00
})
}
// Links
if (Array.isArray(this.options.head.link)) {
this.options.head.link.forEach(link => {
2017-08-19 08:46:58 +00:00
head += `<link data-n-head="true" ${attrsStr(link)}/>`
2017-08-18 16:05:01 +00:00
})
}
// Style
if (Array.isArray(this.options.head.style)) {
2017-08-19 08:46:58 +00:00
this.options.head.style.forEach(style => {
head += `<style data-n-head="true" ${attrsStr(style, ['cssText'])}>${style.cssText || ''}</style>`
2017-08-18 16:05:01 +00:00
})
}
// Script
if (Array.isArray(this.options.head.script)) {
this.options.head.script.forEach(script => {
2017-08-19 08:46:58 +00:00
head += `<script data-n-head="true" ${attrsStr(script, ['innerHTML'])}>${script.innerHTML || ''}</script>`
2017-08-18 16:05:01 +00:00
})
}
// Resource Hints
const clientManifest = this.renderer.resources.clientManifest
if (this.options.render.resourceHints && clientManifest) {
const publicPath = clientManifest.publicPath || '/_nuxt/'
// Pre-Load initial resources
if (Array.isArray(clientManifest.initial)) {
head += clientManifest.initial.map(r => `<link rel="preload" href="${publicPath}${r}" as="script" />`).join('')
}
// Pre-Fetch async resources
if (Array.isArray(clientManifest.async)) {
head += clientManifest.async.map(r => `<link rel="prefetch" href="${publicPath}${r}" />`).join('')
}
}
2017-08-18 16:05:01 +00:00
this.cache.set(url, head)
return head
}
}