how to optimize the performance of web pages? For front-end performance optimization, here are five tips for improving website loading speed: compress and merge files: compress HTML, CSS, JavaScript, and then merge them to reduce HTTP requests. Latency loading: loads content only when needed. lazy loading: images and other media are loaded only when the user scrolls the page. use caching: use browser caching to reduce resource loading time. compressed images: use compressed image formats, such as JPEG, to reduce file size and speed up loading. 1. Compress and merge files you can use tools and plug-ins (such as Gulp, Grunt, Webpack, and so on) to automatically compress and merge files. HTML compression: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HTML compression exampl</title> </head> <body> <h1>This is the title.</h1> <p>This is a passage.</p> </body> </html> CSS compression: body { background-color: #f8f8f8; font-family: Arial, sans-serif; font-size: 16px; } h1 { color: #333; font-size: 28px; } p { color: #666; font-size: 18px; } JavaScript compression: (function() { var message = "Hello World!"; console.log(message); }()); 2. Delayed loading delayed loading can be achieved using JavaScript. <img data-src="image.jpg" alt="Picture"> <script> // wait for the page to be fully loaded before executing the script window.onload = function() { // get all picture tags var images = document.querySelectorAll('img[data-src]'); // traversing the picture tag Array.prototype.forEach.call(images, function(image) { // modify src image.setAttribute('src', image.getAttribute('data-src')); }); }; </script> 3. Lazy load lazy loading can be implemented using JavaScript and plug-ins. Here we use the jQuery plug-in to implement lazy loading. <img data-src="image.jpg" alt="Picture"> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script> <script> $(function() { $("img").lazyload({…

May 2, 2023 0comments 1303hotness 0likes Aaron Read all

Why did the React team discard defaultProps ? in functional components come to a conclusion first, because it is not necessary. in functional components, we can declare default properties in the form of JS default parameters, as follows: function Foo({foo = 1, bar = "hello"}) { let props = {foo, bar}; //... } The advantage of this is that React 's defaultProps is a black box for most teams. if we put the behavior of the default property in the function component definition, it is more controllable from the point of view of code quality. so what was defaultProps designed for? React the team thinks defaultProps is very useful in classes. because props objects are passed to many different methods: life cycle, callback, and so on. Each function has its own context that requires an initial default value. This makes it difficult to implement using the JS default parameter, because you have to copy the same default value in each function. The following is an example: class Foo { static defaultProps = {foo: 1}; componentDidMount() { let foo = this.props.foo; console.log(foo); } componentDidUpdate() { let foo = this.props.foo; console.log(foo); } componentWillUnmount() { let foo = this.props.foo; console.log(foo); } handleClick = () => { let foo = this.props.foo; console.log(foo); } render() { let foo = this.props.foo; console.log(foo); return <div onClick={this.handleClick} />; } } to sum up, the role of defaultProps is that in class components, new default values can be used in each lifecycle and scope of methods. therefore, it has been implemented in subsequent updates of the React team: using…

May 2, 2023 0comments 1326hotness 0likes Aaron Read all

Preface recently started a new project, want to do a good job of code specifications and constraints, in fact, there are a lot of scaffolding, project templates can be used directly, but do-it-yourself, can be completely self-matching. install eslint install and execute yarn add-- dev eslint add .eslintrc.js to the project directory module.exports = { root: true, // specify root as true,eslint to check only the current project directory env: { // provide default global variables to prevent eslint from checking for errors, such as window browser: true, node: true, es6: true, }, extends: [ // inherit the inspection rules recommended by eslint 'eslint:recommended', ], parserOptions: { ecmaVersion: 'latest', // specify the ECMAScript syntax as up-to-date sourceType: 'module', // specify the code as ECMAScript module ecmaFeatures: { jsx: true, // enable jsx }, }, }; add .eslintignore to the project directory, ignoring some directories and files that do not require eslint detection .eslintrc.js node_modules dist .DS_Store *.local install typescript-eslint since the project uses Typescript , you need to change the eslint interpreter. Refer to typescript-eslint . install and execute yarn add-- dev @ typescript-eslint/parser @ typescript-eslint/eslint-plugin change .eslintrc.js module.exports = { root: true, // specify root as true,eslint to check only the current project directory env: { // provide default global variables to prevent eslint from checking for errors, such as window browser: true, node: true, es6: true, }, extends: [ // share the recommended configuration style 'eslint:recommended', 'plugin:@typescript-eslint/recommended', ], parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], parserOptions: { ecmaVersion: 'latest', // specify the ECMAScript syntax as up-to-date sourceType: 'module', // specify the…

May 1, 2023 0comments 1513hotness 0likes Aaron Read all

recently, t3dotgg, a foreign netizen, suggested that React officially use Create React App to create a new project instead of in the document . It is recommended to use Vite to create a new project . Most netizens agree with this: React's new official document is about to be released (99% is now complete). However, Create React App is still recommended in the Beta version of the official document to create a new project. Two additional alternatives are provided: Vite , Parcel . looking at Create React App's Github repository, we can see that it has not been updated for 5 months, accumulating 1500 + issues . on January 31, Dan Abramov, a core member of the React team, responded to this suggestion, explaining the tradeoffs made by React team members and providing some options. Let's take a look at the details (you can skip to the final conclusion)! Evolution of Create React App when Create React App was released in 2016, the environment of the tool was decentralized. If you want to add React to an existing application, you need to add a & lt;script> tag or import from npm, and then adjust the existing build tool configuration. However, if you want to create a new application built only using React from scratch, there is no clear way to do this. before Create React App, you must install a bunch of tools and connect them together, provide correct presets to use JSX, make different configurations for development and production environments, provide correct settings for resource caching, configure linter, etc.,…

May 1, 2023 0comments 1526hotness 0likes Aaron Read all

Preface in the react project, we usually use the axios library, which is a promise-based http library, to interact with the background to obtain data. It can be run on the browser side and in node.js. It has many excellent features, such as intercepting requests and responses, canceling requests, converting json, client defense XSRF, and so on. install / / install using npm Npm install axios / / install using yarn Yarn add axios Undefined introduce in the project root, create a new request folder, and then create a new index.js and an api.js file in it. The index.js file is used to encapsulate our axios,api.js to uniformly manage our interface. / / introduce axios into index.js import axios from 'axios'; / / introduce qs module to serialize data of type post import QS from 'qs'; / / message prompt component of antd, which can be changed according to your own ui component. import { message } from 'antd' switching of environment our project environment may have a development environment, a test environment and a production environment. We match our default interface url prefix through the environment variable of node. Here you need the global variable process of node, and process.env.NODE_ENV to distinguish between a development environment and a production environment. / / Save environment variables const isPrd = process.env.NODE_ENV == 'production'; / / distinguish the basic URL of development environment or production environment export const basciUrl = isPrd ? 'https://www.production.com' : 'http://www.development.com' the basic URL is exported here to prevent resources from being used differently in other places, and…

April 30, 2023 0comments 1451hotness 0likes Aaron Read all

introduction to Axios Axios is a promise-based HTTP library that can be used in browsers and node.js. Features supports node side and browser side supports advanced configurations such as interceptors use Promise to manage asynchrony, bid farewell to traditional callback mode automatically convert JSON data client supports defense of XSRF install yarn installation $ yarn add axios npm installation npm install axios -D 3.bower installation $ bower install axios easy to use aixos can be loaded directly through cdn, for example: <html> <head> <title>The use of Axios</title> <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script> </head> <body> <input type="button" onclick="getList()" value="Click get"/> <div id="content"> </div> <script type="text/javascript"> function getList(){ axios.request({ url:'/article/home/index', method:'get', baseURL:'http://test.mediastack.cn/' }).then( res => { console.log("get res:",res); var str=JSON.stringify(res); document.getElementById("content").innerHTML = str; },error => { console.log("get request failed:",error); document.getElementById("content").innerHTML = error; } ); } </script> </body> </html> axios is encapsulated in react Axios can be encapsulated into a file in react. Through control operations, unified handling of errors, logic, and validation can be achieved, reducing the redundancy and readability of the code. request encapsulation / * * * Network request configuration , / import axios from "axios"; axios.defaults.timeout = 100000; axios.defaults.baseURL = "http://test.mediastack.cn/"; / * * * http request interceptor , / axios.interceptors.request.use( (config) => { config.data = JSON.stringify(config.data); config.headers = { "Content-Type": "application/json", }; return config; }, (error) => { return Promise.reject(error); } ); / * * * http response interceptor , / axios.interceptors.response.use( (response) => { if (response.data.errCode === 2) { console.log("out of date"); } return response; }, (error) => { console.log("request error:", error); } ); / * * * encapsulate the…

April 30, 2023 0comments 1457hotness 0likes Aaron Read all

8 Mock.js installation and use in the process of development, in order to make it easier for the front end to debug the interface alone, Mock.js is often used to intercept Ajax requests and return preset data. This section describes how to use Mock.js in a react project. perform installation: npm install mockjs --save create a new mock.js under src, as follows: import Mock from 'mockjs' const domain = '/api/' // Simulating the getData interface Mock.mock(domain + 'getData', function () { let result = { code: 200, message: 'OK', data: 'test' } return result }) then introduce mock.js: into src/index.js import React from 'react' import ReactDOM from 'react-dom' import App from './App' import { Provider } from 'react-redux' import store from './store' + import './mock' import './common/style/frame.styl' ...(summary) it's so simple. In this way, when a / api/getData is requested in a project, it is intercepted by Mock.js and the data written in mock.js is returned. 9 solve the cross-domain problem of local development in the react development environment, port 3000 is started by default, while the back-end API service may be on port 80 of the machine, so cross-domain problems may occur during ajax requests. Reverse proxy can be implemented with the help of http-proxy-middleware tools. perform installation: npm install http-proxy-middleware --save-dev create a setupProxy.js under src, as follows: const proxy = require('http-proxy-middleware'); module.exports = function (app) { app.use( '^/api', proxy({ target: 'http://localhost', changeOrigin: true }) ) } this code means that as long as the request address starts with "/ api", it will reverse proxy to the http://localhost…

April 26, 2023 0comments 1443hotness 0likes Aaron Read all

the relative basics of the React project have been explained in detail in 1BI 2 of this tutorial. In 3pr 4, continue to explain the advanced part of React. Build the whole family bucket of React project from scratch (1) Build the whole family bucket of React project from scratch (2) before we begin, review the content introduced in the previous article: 1 create React-APP 2 streamlined items 2.1 Delete files 2.2 simplify the code 2.3 use Fragment to remove the outer tag of the component 3 Project directory structure 3.1 introduce global common styles 3.2 support Sass/Less/Stylus 4 routes 4.1 Page build 4.2 use react-router-dom 4.3 Route Jump 5 components introduce 5.1 create header components 5.2 introduce Header components 5.3 components pass parameters 6 React Developer Tools browser plug-in in this second article, continue to share the following: take a peek at it 7 Redux and related plug-ins 7.1 install redux 7.2 install react-redux 7.3 install redux-thunk 7.4 install the browser Redux plug-in 7.5 create store 7.6complex project store decomposition 7.7 docking react-redux with store 7.8 start Redux DevTools 7.9 install using immutable 8 Mock.js installation and use 9 solve the cross-domain problem of local development 10 other commonly used tools 11 complimentary chapter: integrated Ant Design 11.1 install Ant Design 11.2 implement on-demand loading 11.3 Custom theme colors 7 Redux and related plug-ins students who have done vue development know that the corresponding tool for vuex,react is Redux, and of course there are some ancillary tools, such as react-redux, redux-thunk, and immutable. redux involves a lot of content…

April 26, 2023 0comments 1226hotness 0likes Aaron Read all

4 routes 4.1 Page build first, build the home and login pages. src/pages/home/index.js Code: import React, { Component } from 'react' import './home.styl' class Home extends Component { render() { return ( <div className="P-home"> <h1>Home page</h1> </div> ) } } export default Home src/pages/home/home.styl Code .P-home h1 padding: 20px 0 font-size: 30px color: #fff background: #67C23A text-align: center src/pages/login/index.js Code: import React, { Component } from 'react' import './login.styl' class Login extends Component { render() { return ( <div className="P-login"> <h1>Login page</h1> </div> ) } } export default Login src/pages/login/login.styl Code .P-login h1 background: #E6A23C my personal habit is for reference only: className at the global public level (no modularization is required), using G-xxx. For example, G-autocut (truncation), G-color-red (text red). page-level className, using P-xxx. module-level className, using M-xxx. Next, we use react-router-dom to implement routing. 4.2 use react-router-dom execute the installation command: npm install react-router-dom --save modify src/App.js, the code is as follows: import React, { Fragment } from 'react' import Login from './pages/login' import Home from './pages/home' import { HashRouter, Route, Switch, Redirect } from 'react-router-dom' function App() { return ( <Fragment> <HashRouter> <Switch> <Route path="/login" component={Login} /> <Route path="/home" component={Home} /> <Route exact path="/" component={Home} /> <Redirect to={"/home"} /> </Switch> </HashRouter> </Fragment> ) } export default App App.js introduces two page-level components, Home and Login. Then the paths are set using react-router-dom. The mechanism of import is to find index.js by default, so the primary file name of each component is set to index.js, which can be omitted when referenced. explain the attributes of & lt;Route> here:…

April 25, 2023 0comments 1383hotness 0likes Aaron Read all

take a peek at it before we officially begin, let's take a look at what we can learn through this sharing. create a React project from scratch supports Sass/Scss/Less/Stylus Route usage: react-router-dom component creation and reference React Developer Tools browser plug-in redux, react-redux use redux-thunk creation and use of store Redux DevTools installation and use immutable.js uses Mock.js uses resolve local cross-domain reverse proxy Summary of other commonly used tools Super value bonus: integrated Ant Design even if you are a novice, after following the operation, you can quickly get started with the React project! Note: the "+" at the beginning of each line in the code area of this article indicates addition, "-" indicates deletion, and "M" indicates modification. Indicates omission. 1 create React-APP through the official create-react-app, find a favorite directory and execute: npx create-react-app react-app The last react-app of the command is the name of the project, which you can change on your own. wait a moment to complete the installation. After the installation is complete, you can start the project using npm or yarn. enter the project directory and start the project: cd react-app yarn start (or use npm start) if you do not have yarn installed, you can go to the website to install: https://yarnpkg.com after startup, you can access the project at the following address: http://localhost:3000/ 2 streamlined items 2.1 Delete files next, delete the files that are not used in the general project to simplify the project. ├─ /node_modules ├─ package.json ├─ /public | ├─ favicon.ico | ├─ index.html - | ├─ logo192.png…

April 25, 2023 0comments 1526hotness 0likes Aaron Read all