0.0.4 • Published 2 months ago
@substrate-system/preload v0.0.4
preload
Create a link
tag with a preload
attribute, for images.
<link
rel="preload"
as="image"
href="wolf.jpg"
imagesrcset="wolf_400px.jpg 400w, wolf_800px.jpg 800w, wolf_1600px.jpg 1600w"
imagesizes="50vw"
>
To preload responsive images, new attributes were recently added to the
<link>
element:imagesrcset
andimagesizes
Install
npm i -S @substrate-system/preload
Example
This package includes some utilities for working with Cloudinary.
import { Cloudinary } from '@cloudinary/url-gen'
import { preload } from '@substrate-system/preload'
import { defaultSrcset } from '@substrate-system/preload/cloudinary'
// can pass in functions for `srcset` and `href` arguments
const tag:string = preload(
'my-picture.jpg',
getSrcset,
getHref,
'(max-width: 700px) 100vw, 50vw' // sizes
)
// use Cloudinary
const cld = new Cloudinary({
cloud: { cloudName: CLOUD_NAME },
url: { secure: true }
})
function getSrcset (localPath:string):string {
return defaultSrcset(cld, localPath)
}
function getHref (localPath:string):string {
return cld.image(localPath).toURL()
}
API
preload(path, srcset, href, sizes)
Takes either a string or a function for srcset
and href
attributes.
If they are functions, they will be called with the given filepath
.
function preload (
filepath:string,
srcset:((localPath:string)=>string)|string,
href:string|((localPath:string)=>string),
sizes:string = '100vw',
):string
Cloudinary
import {
defaultSrcset,
getSrcset
} from '@substrate-system/preload/cloudinary'
defaultSrcset(cld, filename)
function defaultSrcset (cld:Cloudinary, filename:string):string {
getSrcset(cld, filename, widths)
function getSrcset (
cld:Cloudinary,
filename:string,
widths:number[]
):string[]
Modules
This exposes ESM via package.json exports
field.
ESM
import { preload } from '@substrate-system/preload'
pre-built JS
This package exposes minified JS files too. Copy them to a location that is accessible to your web server, then link to them in HTML.
copy
cp ./node_modules/@substrate-system/preload/dist/index.min.js ./public/preload.min.js
HTML
<script type="module" src="./preload.min.js"></script>
develop
This needs a .env
file in the test
directory.
cp ./test/.env.example ./test/.env