search
HomeWeb Front-endJS TutorialHow to optimize pages in vue (load on demand)

How to optimize pages in vue (load on demand)

Jun 21, 2018 pm 04:22 PM
vuewebpackLoad on demand

This article mainly introduces the on-demand loading of pages (vue webpack) for vue project optimization. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

When writing a single-page application through vue, there may be many routes introduced. When packaged and built, the JavaScript package will become very large and affect loading. It would be more efficient if we could split the components corresponding to different routes into different code blocks, and then load the corresponding components when the route is accessed. This will greatly increase the speed of the first screen display, but may slow down other pages. Combined with Vue's asynchronous components and webpack's code splitting feature, lazy loading of routing components can be easily implemented.

Just like the lazy loading of pictures, if the customer does not see those pictures at all, but we load them all when opening the page, this will greatly increase the request time and reduce the user experience. degree. Lazy loading is used on many websites, such as shopping websites such as Taobao and JD.com. There are many picture links on them. If you pull the scroll down quickly, you may see the pictures loading. Condition.

The same is true for single-page applications. The user may not jump to other pages by clicking, but only stay on the main page. Then we do not need to load all the resources of other pages. If the user clicks in, load again. This can greatly improve the request time and improve the user experience.

Require.ensure() is provided in webpack to implement on-demand loading. In the past, routes were introduced through import, but now they are introduced through const definition.

Introduction method without on-demand loading of pages: import home from '../../common/home.vue'

Introduction method of on-demand loading of pages: const home = r => require.ensure( [], () => r (require('../../common/home.vue')))

The following content explains more For details

webpack ensure I believe everyone has heard of it. Some people call it asynchronous loading, and some people say it does code cutting. So what is this guy used for? In fact, to put it bluntly, it exports the js module to a .js file independently. Then when using this module, webpack will construct a script dom element, and the browser initiates an asynchronous request for the js file.

Scenario analysis:

For example, there is a button on the homepage of the application, which can be clicked to open a certain map. To open the map, we need to use the js of Baidu Map, so we have to package the js of Baidu Map into the home page. A js file of Baidu Map is very large, assuming it is 1m, so it causes the packaging of our home page. js is very large, and it takes a long time for users to open the homepage.

Is there any good solution?

Solution 1

Since the package into the same js is very large, then we can completely classify the Baidu map js and use the browser's concurrent request js file processing , in this case, it will take much less time than loading a js file. Well, this is also a good plan. Just configure a new entry for baidumap.js, so that it can be packaged into two js files and inserted into HTML (if baidumap.js is referenced by multiple entry files, you do not need to set it as the entry file. And just use CommonsChunkPlugin directly and export it to a public module) You can refer to my previous article webpack module packaging

Is there a better solution?

Solution 2

Of course there is still one! If we think about it carefully, Baidu Map only pops up after the user clicks it. In other words, this function is optional. Then the solution comes. Can I download the js of Baidu Map when the user clicks? Of course it can. So how to download the js of Baidu map when the user clicks? Therefore, we can write a button listener

mapBtn.click(function() {
 //获取 文档head对象
 var head = document.getElementsByTagName('head')[0];
 //构建 <script>
 var script = document.createElement(&#39;script&#39;);
 //设置src属性
 script.async = true;
 script.src = "http://map.baidu.com/.js"
 //加入到head对象中
 head.appendChild(script);
})

The above few lines of code are not difficult for everyone. You can load the Baidu map when you click it. After the Baidu map is loaded, you can use the objects of the Baidu map to perform our operations. ok, at this point the principle of webpack.ensure has been explained more than half. It is
to separate some js modules into js files, and then when needed, create a script object and add it to the document.head object. The browser will automatically initiate a request for us. Request this js file and write a callback to define what business logic operations need to be done after getting this js file.

ok, then we will use webpack's API to help us accomplish such a thing. The Baidu map js is loaded asynchronously after clicking. We wrote it ourselves when we clicked to load the js above. Webpack can easily help us handle such a thing, instead of having to hand-write

mapBtn.click(function() {
 require.ensure([], function() {
  var baidumap = require(&#39;./baidumap.js&#39;) //baidumap.js放在我们当前目录下
 })
})

! Of course, let’s analyze it. The require.ensure function is a dividing line for code separation, indicating that the require in the callback is what we want to separate out, that is, require('./baidumap.js'), which separates baidumap.js to form a webpack package separate js file. Of course, you can also write some synchronous requirements in ensure, such as

var sync = require(&#39;syncdemo.js&#39;)  //下面ensure里面也用到
mapBtn.click(function() {
 require.ensure([], function() {
  var baidumap = require(&#39;./baidumap.js&#39;) //baidumap.js放在我们当前目录下
  var sync = require(&#39;syncdemo.js&#39;) //这个不会独立出去,因为它已经加载到模块缓存中了
 })
})

也就是说,ensure会把没有使用过的require资源进行独立分成成一个js文件. require.ensure的第一个参数是什么意思呢?[], 其实就是 当前这个 require.ensure所依赖的其他 异步加载的模块。你想啊?如果A 和 B都是异步加载的,B中需要A,那么B下载之前,是不是先要下载A啊?,所以ensure的第一个参数[]是它依赖的异步模块,但是这里需要注意的是,webpack会把参数里面的依赖异步模块和当前的需要分离出去的异步模块给一起打包成同一个js文件,这里可能会出现一个重复打包的问题,假设A 和 B都是异步的, ensure A 中依赖B,ensure B中 依赖A,那么会生成两个文件,都包含A和B模块。 如果想加载A require.ensure([‘A.js'],function) 即可

说完了上面的原理。下面就实践一下

entry.js 依赖三个 js。

  1. Abtn-work.js 是封装了 abtn按钮点击后,才执行的业务逻辑

  2. Bbtn-work.js 是封装了 bbtn按钮点击后,才执行的业务逻辑

  3. util.js 是封装了 entry.js需要利用的工具箱

针对上面的需求,优化方案

假设 Abtn-work.js Bbtn-work.js util.js都是非常大的文件因为 Abtn-work.js Bbtn-work.js 都不是entry.js必须有的,即可能发生的操作,那么我们把他们利用异步加载,当发生的时候再去加载就行了

util.js是entry.js立即马上依赖的工具箱。但是它又非常的大,所以将其配置打包成一个公共模块,利用浏览器的并发加载,加快下载速度。ok,构思完成,开始实现

index.html

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>index</title>
 </head>
 <body>
  <p id="aBtn">Abtn</p>
  <p id="bBtn">Bbtn</p>
 </body>
</html>

定义了两个buttom

然后看看 entry.js

var util_sync = require(&#39;./util-sync.js&#39;)
alert(util_sync.data)
document.getElementById("aBtn").onclick = function() {
 require.ensure([], function() {
  var awork = require(&#39;./workA-async.js&#39;)
  alert(awork.data)
  //异步里面再导入同步模块--实际是使用同步中的模块
  var util1 = require(&#39;./util-sync.js&#39;)
 })
}
document.getElementById("bBtn").onclick = function() {
 require.ensure([], function() {
  var bwork = require(&#39;./workB-async.js&#39;)
  alert(bwork.data)
 })
}

可以看到,workA-async.js, workB-async.js 都是点击后才ensure进来的。什么时候加载完成呢?就是 require.ensure() 第二个函数参数,即回调函数,它表示当下载js完成后,发生的因为逻辑

webpack打包后,形成

其实, 1.1… 2.2…就是我们ensure导出来的js文件

我们看看代码是如何加载的执行的,点击打包插入js后的html

可以看到,并没有加载 ensure导出来的 1.1…js 2.2…js

点击 abtn,

发现浏览器下载并加载了 1.1…js

点击 bbtn

发现浏览器下载并加载了 2.2…js

vue项目优化,还有通过减少向服务器请求的次数来减少等待的时间。比如,一个页面的数据包括图片、文字等用户都已经加载完了,然后用户通过点击跳转到了另外一个界面。然后从另外一个界面通过返回又回到了原先的界面。如果没有设置的话,那么原先界面的信息就要重新向服务器请求得到。而通过vue提供的keep-alive可以是页面的已经请求的数据得以保存,减少请求的次数,提高用户的体验程度。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用VS Code编辑器如何开发AngularJS 2应用程序

在Angular中有关管道操作符(|)用法

在Vue中有关SPA首屏加载优化(详细教程)

VS Code编辑器中关于修改选中文字或代码颜色操作

The above is the detailed content of How to optimize pages in vue (load on demand). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.