Skip to content

Instantly share code, notes, and snippets.

@Accudio
Last active Sep 25, 2021
Embed
What would you like to do?
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