Skip to content

Commit

Permalink
feat: add preload functionality (#444)
Browse files Browse the repository at this point in the history
  • Loading branch information
codeflorist committed Jan 13, 2022
1 parent b117477 commit 6f245c6
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
8 changes: 8 additions & 0 deletions docs/content/en/2.components/1.nuxt-img.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,11 @@ Using the `modifiers` prop lets you use any of these transformations.
:modifiers="{ roundCorner: '0:100' }"
/>
```

### `preload`

In case you want to preload the image, use this prop. This will place a corresponding `link` tag in the page's head.

```html
<nuxt-img preload src="/nuxt-icon.png" />
```
1 change: 1 addition & 0 deletions src/runtime/components/image.mixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const imageMixin = defineMixin({
provider: { type: String, default: undefined },

sizes: { type: [Object, String] as unknown as () => string | Record<string, any>, default: undefined },
preload: { type: Boolean, default: undefined },

// <img> attributes
width: { type: [String, Number], default: undefined },
Expand Down
13 changes: 13 additions & 0 deletions src/runtime/components/nuxt-img.vue
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,19 @@ type NAttrs = typeof imageMixin['nImgAttrs'] & {
export default defineComponent({
name: 'NuxtImg',
mixins: [imageMixin],
head () {
if (this.preload === true) {
return {
link: [
{
rel: 'preload',
as: 'image',
href: this.nSrc
}
]
}
}
},
computed: {
nAttrs (): NAttrs {
const attrs: NAttrs = this.nImgAttrs
Expand Down
16 changes: 16 additions & 0 deletions src/runtime/components/nuxt-picture.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@ export default defineComponent({
legacyFormat: { type: String, default: null },
imgAttrs: { type: Object, default: null }
},
head () {
if (this.preload === true) {
const srcKey = typeof this.nSources[1] !== 'undefined' ? 1 : 0
const link = {
rel: 'preload',
as: 'image',
imagesrcset: this.nSources[srcKey].srcset
}
if (typeof this.nSources[srcKey].sizes !== 'undefined') {
link.imagesizes = this.nSources[srcKey].sizes
}
return {
link: [link]
}
}
},
computed: {
isTransparent (): boolean {
return ['png', 'webp', 'gif'].includes(this.originalFormat)
Expand Down

0 comments on commit 6f245c6

Please sign in to comment.