Skip to content

Instantly share code, notes, and snippets.

@Accudio
Last active September 25, 2021 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Accudio/f7625f4d67ec3598e9f06e9b63b2552a to your computer and use it in GitHub Desktop.
Save Accudio/f7625f4d67ec3598e9f06e9b63b2552a to your computer and use it in GitHub Desktop.
Example Eleventy shortcode abstraction of an Image CDN. Built with CloudImage and an alias in mind, customise as your setup and provider.
{% image {
src: 'otter.jpg'
alt: 'an otter standing on a log looking majestic'
srcset: [300, 450, 600, 800, 1000, 1200]
sizes: '100vw'
width: 1200
height: 800
loading: 'lazy'
class: 'image-class'
} %}
const CDN_BASE = 'https://example.imagecdn.com'
function image(opts) {
if (!opts.src) return console.error('Image: src argument required')
if (!opts.width) return console.error('Image: width argument required')
if (!opts.height) return console.error('Image: height argument required')
// set defaults here
const args = {
alt: '',
srcset: [300, 450, 600, 800, 1000, 1200],
sizes: '(min-width: 82rem) 80rem, calc(100vw - 2rem)',
loading: 'lazy',
class: false,
picClass: false,
lowdpiQuality: 80,
hidpiQuality: 40,
...opts
}
const path = `/cdn/${args.src}`
const fallback = createSrc(path, args.srcset.at(-1), args.lowdpiQuality)
const srcset = createSrcset(path, args.srcset, args.lowdpiQuality)
const hidpiSrcset = createSrcset(path, args.srcset, args.hidpiQuality)
const markup = `
<picture${args.picClass ? ' class="' + args.picClass + '"' : ''}>
<source media="(-webkit-min-device-pixel-ratio: 1.5)" srcset="${hidpiSrcset}" sizes="${args.sizes}">
<img${args.class ? ' class="' + args.class + '"' : ''} alt="${args.alt}" src="${fallback}" srcset="${srcset}" sizes="${args.sizes}" width="${args.width}" height="${args.height}" loading="${args.loading}" decoding="async">
</picture>
`
return markup
}
// customise this function depending on your image CDN and setup
function createSrc(path, width, quality) {
return `${CDN_BASE}${path}?w=${width}&q=${quality}`
}
function createSrcset(path, widths, quality) {
const srcsetArr = widths.map(width => {
const url = createSrc(path, width, quality)
return `${url} ${width}w`
})
return srcsetArr.join(',')
}
module.exports = image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment