Skip to content

Commit

Permalink
Merge pull request #11 from ethanniser/prefetch-product-images
Browse files Browse the repository at this point in the history
prefetch product images
  • Loading branch information
RhysSullivan authored Oct 20, 2024
2 parents 28fc436 + 8eaf5f6 commit ae0e22d
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions src/components/ui/product-card.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
"use client";
import { Link } from "@/components/ui/link";
import Image from "next/image";
import NextImage from "next/image";
import { getImageProps } from "next/image";
import { Product } from "@/db/schema";
import { useEffect } from "react";

export function ProductLink(props: {
imageUrl?: string | null;
category_slug: string;
Expand All @@ -9,14 +13,33 @@ export function ProductLink(props: {
product: Product;
}) {
const { category_slug, subcategory_slug, product, imageUrl } = props;

// prefetch the main image for the product page, if this is too heavy
// we could only prefetch the first few cards, then prefetch on hover
const prefetchProps = getImageProps({
height: 256,
quality: 80,
width: 256,
src: imageUrl ?? "/placeholder.svg?height=64&width=64",
alt: `A small picture of ${product.name}`,
});
useEffect(() => {
try {
const url = prefetchProps.props.src;
const img = new Image();
img.src = url;
} catch (e) {
console.error("failed to preload", prefetchProps.props.src, e);
}
});
return (
<Link
prefetch={true}
className="group flex h-[130px] w-full flex-row border px-4 py-2 hover:bg-gray-100 sm:w-[250px]"
href={`/products/${category_slug}/${subcategory_slug}/${product.slug}`}
>
<div className="py-2">
<Image
<NextImage
loading={props.loading}
decoding="sync"
src={imageUrl ?? "/placeholder.svg?height=48&width=48"}
Expand Down

0 comments on commit ae0e22d

Please sign in to comment.