ماه گذشته، سایت تجارت الکترونیک ما با زمان بارگذاری 6.5 ثانیه دست و پنجه نرم می کرد. امروز در 2.1 ثانیه بارگیری می شود. در اینجا دقیقاً چگونه این کار را انجام دادیم، با نمونههای کد واقعی و نتایج.
اکنون CSS بحرانی را درون خط می کنیم و سبک های غیر بحرانی را به تعویق می اندازیم:
/* Only styles needed for above-the-fold content */.hero{...}.nav{...}rel="preload"href="styles.css"as="style"onload="this.onload=null;this.rel="stylesheet""/>
"module">// Dynamic import when neededconstshowSlider=async ()=>{const{createSlider}=awaitimport('./tiny-slider.js');createSlider();}// Load on user interactiondocument.querySelector('.slider-btn').addEventListener('click',showSlider);
نتیجه: حجم بار جاوا اسکریپت 65 درصد کاهش یافت
4. استراتژی ذخیره هوشمند 🧠
// Service Worker SetupconstCACHE_VERSION='v1.2.0';constCACHED_ASSETS=['/','/styles.css','/app.js','/fonts/roboto.woff2'];self.addEventListener('install',event=>{event.waitUntil(caches.open(CACHE_VERSION).then(cache=>cache.addAll(CACHED_ASSETS)));});
نتیجه: بازدیدهای مکرر 80 درصد سریعتر بارگیری میشوند
5. بهینه سازی بارگذاری فونت 📝
rel="preload"href="/fonts/roboto.woff2"as="font"type="font/woff2"crossorigin/>/* Font loading strategy */@font-face{font-family:'Roboto';font-display:swap;src:url('/fonts/roboto.woff2')format('woff2');}
نتیجه: دیگر خبری از سوسو زدن فونت نیست، نمایش متن سریعتر
// Prefetch on hoverconstprefetchOnHover=(event)=>{constlink=event.target.closest('a');if (link&&!prefetched.has(link.href)){constprefetcher=document.createElement('link');prefetcher.rel='prefetch';prefetcher.href=link.href;document.head.appendChild(prefetcher);prefetched.add(link.href);}}document.addEventListener('mouseover',prefetchOnHover);
نتیجه: انتقال صفحه فورا احساس می شود
8. API Response Optimization 📡
// Implementing field selectionconstfetchProduct=async (id)=>{constfields=['name','price','thumbnail'];constresponse=awaitfetch(`/api/products/${id}?fields=${fields.join(',')}`);returnresponse.json();}
نتیجه: پاسخ های API 60٪ کوچکتر است
9. رژیم غذایی مدیریت دولتی 🏃♂️
// Before: Everything in Reduxconststore=createStore(rootReducer);// After: Only what's neededfunctionProductPage(){const[product,setProduct]=useState(null);constglobalCart=useSelector(state=>state.cart);// Local state for UIconst[isLoading,setIsLoading]=useState(false);const[selectedVariant,setSelectedVariant]=useState(null);// ...}