前端 SSG:别让你的网站加载速度慢得像蜗牛

前端 SSG:别让你的网站加载速度慢得像蜗牛

毒舌时刻

这网站加载速度慢得能让我泡杯咖啡回来还没好。

各位前端同行,咱们今天聊聊前端 SSG(静态站点生成)。别告诉我你还在使用纯客户端渲染,那感觉就像在没有预加载的情况下开车——能开,但起步慢得要命。

为什么你需要 SSG

最近看到一个项目,每次加载都要重新获取数据,用户体验差。我就想问:你是在做网站还是在做实时应用?

反面教材

// 反面教材:纯客户端渲染 // App.jsx import React, { useState, useEffect } from 'react'; function App() { const [posts, setPosts] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchPosts() { setLoading(true); try { const response = await fetch('https://api.example.com/posts'); const data = await response.json(); setPosts(data); } catch (error) { console.error('Error fetching posts:', error); } finally { setLoading(false); } } fetchPosts(); }, []); return ( <div> <h1>我的博客</h1> {loading ? <div>加载中...</div> : ( <div> {posts.map(post => ( <div key={post.id}> <h2>{post.title}</h2> <p>{post.content}</p> </div> ))} </div> )} </div> ); } export default App; 

毒舌点评:这代码,就像在每次启动时都要重新启动发动机,慢得要命。

正确姿势

1. Next.js SSG

// 正确姿势:Next.js SSG // 1. 安装依赖 // npx create-next-app@latest // 2. 页面组件 // pages/index.js import React from 'react'; export async function getStaticProps() { // 构建时获取数据 const res = await fetch('https://api.example.com/posts'); const posts = await res.json(); return { props: { posts }, revalidate: 60 // 每 60 秒重新生成 }; } export default function Home({ posts }) { return ( <div> <h1>我的博客</h1> <div> {posts.map(post => ( <div key={post.id}> <h2>{post.title}</h2> <p>{post.content}</p> </div> ))} </div> </div> ); } // 3. 动态路由 // pages/posts/[id].js import React from 'react'; export async function getStaticPaths() { // 构建时生成所有可能的路径 const res = await fetch('https://api.example.com/posts'); const posts = await res.json(); const paths = posts.map(post => ({ params: { id: post.id.toString() } })); return { paths, fallback: false }; } export async function getStaticProps({ params }) { // 构建时获取数据 const res = await fetch(`https://api.example.com/posts/${params.id}`); const post = await res.json(); return { props: { post } }; } export default function Post({ post }) { return ( <div> <h1>{post.title}</h1> <p>{post.content}</p> </div> ); } 

2. Astro SSG

// 正确姿势:Astro SSG // 1. 安装依赖 // npm create astro@latest // 2. 页面组件 // src/pages/index.astro --- // 构建时获取数据 const res = await fetch('https://api.example.com/posts'); const posts = await res.json(); --- <html> <head> <title>我的博客</title> </head> <body> <h1>我的博客</h1> <div> {posts.map(post => ( <div key={post.id}> <h2>{post.title}</h2> <p>{post.content}</p> </div> ))} </div> </body> </html> // 3. 动态路由 // src/pages/posts/[id].astro --- // 构建时获取数据 const { id } = Astro.params; const res = await fetch(`https://api.example.com/posts/${id}`); const post = await res.json(); --- <html> <head> <title>{post.title}</title> </head> <body> <h1>{post.title}</h1> <p>{post.content}</p> </body> </html> 

3. Gatsby SSG

// 正确姿势:Gatsby SSG // 1. 安装依赖 // npm install -g gatsby-cli // gatsby new my-site // 2. 配置数据源 // gatsby-config.js module.exports = { plugins: [ { resolve: 'gatsby-source-rest-api', options: { endpoints: ['https://api.example.com/posts'] } } ] }; // 3. 页面组件 // src/pages/index.js import React from 'react'; import { graphql } from 'gatsby'; export const query = graphql` query { allRestApiPosts { edges { node { id title content } } } } `; export default function Home({ data }) { const posts = data.allRestApiPosts.edges.map(edge => edge.node); return ( <div> <h1>我的博客</h1> <div> {posts.map(post => ( <div key={post.id}> <h2>{post.title}</h2> <p>{post.content}</p> </div> ))} </div> </div> ); } // 4. 动态页面 // src/templates/post.js import React from 'react'; import { graphql } from 'gatsby'; export const query = graphql` query($id: String!) { restApiPosts(id: { eq: $id }) { title content } } `; export default function Post({ data }) { const post = data.restApiPosts; return ( <div> <h1>{post.title}</h1> <p>{post.content}</p> </div> ); } // 5. 创建动态页面 // gatsby-node.js exports.createPages = async ({ graphql, actions }) => { const { createPage } = actions; const result = await graphql(` query { allRestApiPosts { edges { node { id } } } } `); result.data.allRestApiPosts.edges.forEach(edge => { createPage({ path: `/posts/${edge.node.id}`, component: path.resolve('./src/templates/post.js'), context: { id: edge.node.id } }); }); }; 

毒舌点评:这才叫前端 SSG,构建时生成静态页面,加载速度快,用户体验好,再也不用担心页面加载慢的问题了。

Read more

前端防范 XSS(跨站脚本攻击)

目录 一、防范措施 1.layui util  核心转义的特殊字符 示例 2.js-xss.js库 安装 1. Node.js 环境(npm/yarn) 2. 浏览器环境 核心 API 基础使用 1. 基础过滤(默认规则) 2. 自定义过滤规则 (1)允许特定标签 (2)允许特定属性 (3)自定义标签处理 (4)自定义属性处理 (5)转义特定字符 常见场景示例 1. 过滤用户输入的评论内容 2. 允许特定富文本标签(如富文本编辑器内容) 注意事项 更多配置 XSS(跨站脚本攻击)是一种常见的网络攻击手段,它允许攻击者将恶意脚本注入到其他用户的浏览器中。

详细教程:如何从前端查看调用接口、传参及返回结果(附带图片案例)

详细教程:如何从前端查看调用接口、传参及返回结果(附带图片案例)

目录 1. 打开浏览器开发者工具 2. 使用 Network 面板 3. 查看具体的API请求 a. Headers b. Payload c. Response d. Preview e. Timing 4. 实际操作步骤 5. 常见问题及解决方法 a. 无法看到API请求 b. 请求失败 c. 跨域问题(CORS) 作为一名后端工程师,理解前端如何调用接口、传递参数以及接收返回值是非常重要的。下面将详细介绍如何通过浏览器开发者工具(F12)查看和分析这些信息,并附带图片案例帮助你更好地理解。 1. 打开浏览器开发者工具 按下 F12 或右键点击页面选择“检查”可以打开浏览器的开发者工具。常用的浏览器如Chrome、Firefox等都内置了开发者工具。下面是我选择我的一篇文章,打开开发者工具进行演示。 2. 使用

Cursor+Codex隐藏技巧:用截图秒修前端Bug的保姆级教程(React/Chakra UI案例)

Cursor+Codex隐藏技巧:用截图秒修前端Bug的保姆级教程(React/Chakra UI案例) 前端开发中最令人头疼的莫过于那些难以定位的UI问题——元素错位、样式冲突、响应式失效...传统调试方式往往需要反复修改代码、刷新页面、检查元素。现在,通过Cursor编辑器集成的Codex功能,你可以直接用截图交互快速定位和修复这些问题。本文将带你从零开始,掌握这套革命性的调试工作流。 1. 环境准备与基础配置 在开始之前,确保你已经具备以下环境: * Cursor编辑器最新版(v2.5+) * Node.js 18.x及以上版本 * React 18项目(本文以Chakra UI 2.x为例) 首先在Cursor中安装Codex插件: 1. 点击左侧扩展图标 2. 搜索"Codex"并安装 3. 登录你的OpenAI账户(需要ChatGPT Plus订阅) 关键配置项: // 在项目根目录创建.