I've got a live site https://courageous-kulfi-58c13b.netlify.app/. Whenever a checkbox is clicked, it should turn green with a tick svg on it. However, on the first app load, clicking a checkbox will show a noticeable delay between the background turning green and the tick svg actually showing. NextJS only requests for the svg once I click on the checkbox. The svg is used in my css as a background image in a ::before
pseudo element. How can I make next request for the svg in initial render so there isn't this delay?
const Checkbox = (props: Props) => {
const [checked, setChecked] = useState(false);
const handleClick = () => {
setChecked((prevChecked) => !prevChecked);
};
return (
<>
<input
type="checkbox"
onClick={handleClick}
className={cn({
"before:bg-tick": checked,
})}
></input>
</>
);
};
tailwind.config.js
module.exports = {
extend: {
backgroundImage: {
tick: "url(/Tick.svg)",
},
}
}
CodePudding user response:
You can inline the svg with something like the following. Then there will be no delay in downloading the svg.
.tick:before {
content: url('data:image/svg xml; utf8, <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 342.357 342.357" style="enable-background:new 0 0 342.357 342.357" xml:space="preserve"><path d="M290.04 33.286 118.861 204.427l-66.541-66.52L0 190.226l118.862 118.845L342.357 85.606z"/></svg>');
}
Note I have run the svg through svgo
to optimize it.
Example here: https://play.tailwindcss.com/TlRvKKs53I?file=css
Preload image
The other option would be to preload the image in the html head.
<link rel="preload" as="image" href="/Tick.svg">
The old school hacky way was to include an image tag on the page somewhere, but use css to make it not visible, but the browser would still load it.