简体   繁体   中英

Why does my image take a long time to download for my SPA?

I'm building a react SPA and I want an image as the background on my homepage. the image is 1.2mb and there is a clear lag when it first loads, it even loads in black and white and then flicks to color

so I've tried a few things. I've compressed it. it's now 700kb. I've added it to an s3 bucket instead of having it locally. and I created a cloudfront distribution which I'm requesting it from instead. obviously the image is fine once downloaded and I flick between different pages in my app and back to the homepage, because presumably the browser has cached. however, when I hard reload it always seems a bit delayed. oh and I also added a cache control tag to the object in my bucket. is there anyway I can fix this or make it load quicker?

oh and some code:

const Container = styled.div`
    background-image: url(cloudfront.net/beach.jpg);
    background-size: cover;
    height: 100%;
    position: absolute;

    width: 100%;

    &:before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background-image: linear-gradient(to bottom right, #000, #fff);
        opacity: 0.2;
    }
`

I'm actually applying it to the component itself rather than the direct html or body elements

There are actually strategies when it comes to optimising images, but let me list down 2 of the most immediate ones that you can adopt.

1) Instead of using traditional image formats such as jpeg and png , you might want to consider using webp , as it offers better compression than the former.

However, do take note that browser support , as it is still not supported by Safari. You can consider using a fallback image formats for browsers that do not support webp .

2) Fetching of images based on viewport size. You can store images of various sizes, and ensure that your app to fetches the right image based on the viewport size. For instance, on mobile devices, you should be fetching smaller images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM