Ways to optimize front-end loading speed

Table of contents

introduction

1. Compress and combine resources

1.1 Minify JavaScript and CSS

Sample code:

1.2 Merge files

Sample code:

2. Use CDN to accelerate

Sample code:

3. Using cache

3.1 Using HTTP cache

Sample code:

3.2 Use Service Worker cache

Sample code:

4. Use asynchronous loading

4.1 Using the defer attribute

Sample code:

4.2 Using dynamic loading

Sample code:

5. Image optimization

5.1 Use appropriate image formats

5.2 Compressing images

5.3 Responsive images

5.4 Lazy loading images

Sample code:

6. Use Font Icons

7. Lazy loading non-critical resources

8. Use Gzip compression

9. Advise users to cache

10. Use asynchronous loading of third-party scripts

in conclusion


introduction

In today's internet age, the loading speed of a website is crucial to user experience and SEO (Search Engine Optimization). Fast-loading web pages attract more visitors and increase user satisfaction. For front-end developers, optimizing front-end loading speed is an essential skill. This article will introduce some methods and techniques to optimize the front-end loading speed to help you improve the performance and user experience of your website.

1. Compress and combine resources

First, we can reduce the loading time of web pages by compressing and merging front-end resource files. Compressing JavaScript, CSS, and HTML files reduces file size, resulting in faster downloads. Merging multiple files into one file can reduce the number of network requests and further improve the loading speed.

1.1 Minify JavaScript and CSS

Use minification tools such as UglifyJS and CleanCSS to minify JavaScript and CSS files. These tools reduce file size by removing whitespace, comments, and unnecessary characters from code.

Sample code:

 
 
# 使用UglifyJS压缩JavaScript文件
uglifyjs input.js -o output.js

# 使用CleanCSS压缩CSS文件
cleancss input.css -o output.css

1.2 Merge files

Combining multiple JavaScript or CSS files into one file can reduce the number of network requests and thus improve loading speed.

Sample code:

 
 
<!-- 合并前 -->
<link rel="stylesheet" href="style1.css">
<link rel="stylesheet" href="style2.css">
<link rel="stylesheet" href="style3.css">

<!-- 合并后 -->
<link rel="stylesheet" href="styles.css">
 
 
<!-- 合并前 -->
<script src="script1.js"></script>
<script src="script2.js"></script>
<script src="script3.js"></script>

<!-- 合并后 -->
<script src="scripts.js"></script>

2. Use CDN to accelerate

Using a CDN (Content Delivery Network) can speed up the loading of static resources, thereby improving the loading speed of web pages. CDN stores the static resources of the website on servers distributed all over the world, and users can obtain resources from the nearest server, reducing transmission time and delay.

When using CDN, make sure to use a stable and reliable CDN service provider, and select an appropriate resource reference address.

Sample code:

 
 
<!-- 使用CDN加速jQuery的加载 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>

<!-- 使用CDN加速Bootstrap的加载 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

3. Using cache

Reasonable use of cache is an important means to optimize front-end loading speed. By caching static resources, you can reduce the number of requests to the server, thereby speeding up the loading of web pages.

3.1 Using HTTP cache

Use the Cache-Control and Expires fields in the HTTP header to control the resource's cache policy. Setting an appropriate cache policy allows the browser to use cached resources within a certain period of time without re-downloading.

Sample code:

 
 
// 在服务器端设置Cache-Control和Expires字段
app.get('/static/style.css', (req, res) => {
  res.setHeader('Cache-Control', 'public, max-age=31536000');
  res.setHeader('Expires', new Date(Date.now() + 31536000000).toUTCString());
  res.sendFile('style.css', { root: 'public' });
});

3.2 Use Service Worker cache

Use Service Worker to implement more powerful caching functions on the client side, including offline caching and dynamic caching. Service Worker is a page-independent JavaScript thread that intercepts and processes network requests to enable advanced caching.

Sample code:

 
 
// 注册Service Worker
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then(registration => {
        console.log('Service Worker 注册成功!', registration);
      })
      .catch(error => {
        console.log('Service Worker 注册失败:', error);
      });
  });
}
 
 
// 编写Service Worker脚本(sw.js)
const CACHE_NAME = 'my-cache-v1';
const urlsToCache = [
  '/',
  '/style.css',
  '/script.js'
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(urlsToCache))
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        return response || fetch(event.request);
      })
  );
});

4. Use asynchronous loading

Using asynchronous loading can increase the initial loading speed of the page by loading certain resources after the page has finished loading. Especially for large JavaScript files and non-critical resources, using asynchronous loading can reduce blocking and improve user experience.

4.1 Using the defer attribute

Using <script>the defer attribute of the tag allows the script to be executed after the page is parsed, without blocking the loading of the page.

Sample code:

 
 
<!-- 正常加载 -->
<script src="script.js"></script>

<!-- 使用defer属性 -->
<script src="script.js" defer></script>

4.2 Using dynamic loading

Resources dynamically loaded via JavaScript can be reloaded when needed without affecting the initial load of the page.

Sample code:

 
 
// 动态加载JavaScript
function loadScript(url) {
  const script = document.createElement('script');
  script.src = url;
  document.body.appendChild(script);
}

// 在需要时加载脚本
loadScript('script.js');
 
 
// 动态加载CSS
function loadStyle(url) {
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = url;
  document.head.appendChild(link);
}

// 在需要时加载样式表
loadStyle('style.css');

5. Image optimization

Images are resources that occupy a large amount of size on a web page. Optimizing images can significantly improve the loading speed of web pages.

5.1 Use appropriate image formats

Choosing an appropriate image format can reduce file size. Generally speaking, the JPEG format is suitable for storing photos and complex images, while the PNG format is suitable for storing simple icons and line images.

5.2 Compressing images

Using an image compression tool (such as TinyPNG) can reduce the image file size without affecting the quality of the image.

5.3 Responsive images

Using responsive images can load images of different sizes according to the screen size of the device, avoiding loading too large images.

 
 
<!-- 使用srcset属性定义不同尺寸的图片 -->
<img src="image.jpg" srcset="image.jpg 1x, [email protected] 2x, [email protected] 3x" alt="图片">

5.4 Lazy loading images

Use lazy loading to delay the loading of images, and only load images when they appear in the viewable area.

Sample code:

 
 
<!-- 使用loading属性开启懒加载 -->
<img src="image.jpg" alt="图片" loading="lazy">

6. Use Font Icons

Using font icons can replace traditional picture icons, they have vector characteristics, can be adjusted and styled through CSS, and also reduce the download of pictures.

Commonly used font icon libraries include Font Awesome and Material Icons.

 
 
<!-- 引入Font Awesome图标 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
 
 
<!-- 使用Font Awesome图标 -->
<i class="fas fa-search"></i>

7. Lazy loading non-critical resources

For some non-critical resources, such as pictures at the bottom of the page or third-party scripts, you can use lazy loading to improve the initial loading speed of the page.

 
 
<!-- 使用loading属性开启延迟加载 -->
<img src="image.jpg" alt="图片" loading="lazy">
<script src="third-party.js" defer></script>

8. Use Gzip compression

Using Gzip compression can reduce the file size, thus speeding up the transfer of files. Most modern servers and browsers support Gzip compression.

Enabling Gzip compression on the server side can be achieved by configuring the server, such as Nginx or Apache. In front-end development, you can also use build tools such as Webpack to enable Gzip compression.

9. Advise users to cache

Using technologies such as Service Worker or LocalStorage can allow users to cache web pages, thereby speeding up the loading speed of secondary visits. The caching policy should be set according to the update frequency of web page content, so as to ensure that users can obtain the latest content in time when accessing expired cache.

10. Use asynchronous loading of third-party scripts

For some third-party scripts, such as social media plug-ins, advertising codes, etc., you can use asynchronous loading to avoid blocking page loading. In this way, even if the third-party script fails to load, it will not affect the normal display of the web page.

 
 
<!-- 使用async属性进行异步加载 -->
<script src="third-party.js" async></script>

in conclusion

Optimizing front-end loading speed is an important means to improve web page performance and user experience. This article introduces some methods and techniques to optimize front-end loading speed, including compressing and merging resources, using CDN acceleration, using caching, using asynchronous loading, image optimization, using font icons, using Gzip compression, recommending user caching, and using asynchronous loading third-party script etc. By applying these methods reasonably, you can greatly increase the loading speed of your website, provide users with a better access experience, and also help improve your website’s SEO ranking. I hope this article is helpful to you in optimizing front-end loading speed, and I wish your website to a higher level!

Guess you like

Origin blog.csdn.net/m0_68036862/article/details/131978299