Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce loading time of flutter web app

As of now, we can launch a flutter web app as a single file that will load at once hence taking a lot of time and bandwidth to load which is not ideal, is there any way to load only a single page at a time, not the whole web app. By this I mean, load a widget at a time.

Any suggestions will be appreciated.

like image 975
UTKARSH Sharma Avatar asked May 12 '20 15:05

UTKARSH Sharma


2 Answers

after spending a lot of hours trying to solve this situation, I found a solution to speed up the first load of the app. I saw that my main.dart.js was being downloaded and then, after that, the main.dart.js was triggering the download of the canvaskit.wasm file, this means that my app was starting on a cascade mode, avoiding downloading both files in parallel.

So my solution, after many many many attempts is based on adding only 2 lines of code to the index.html file (.../project_folder/web/index.html). Inside the <head>...</head> tag insert this two lines:

<script src="https://unpkg.com/[email protected]/bin/canvaskit.js"></script>
<link rel="preload" href="https://unpkg.com/[email protected]/bin/canvaskit.wasm" as="fetch" crossOrigin="anonymous">

I know hardcoding these URLs it's not a good practice, but, you will only need to change them if you update Flutter. I'm using Flutter 2.10.1 that uses CanvasKit 0.30.0, and when you build the web app, the generated main.dart.js has a hardcoded URL inside.

If you are going to add those 2 lines to your index.html file, I recommend you to build the web app, and open the main.dart.js file and search for "canvaskit-wasm", there you will find which is the URL you should use (something like "https://unpkg.com/[email protected]/bin/").

It's giving me a good improvement for the initial loading time! So, hope it works for you too!

like image 194
ALNAJJAR Avatar answered Nov 15 '22 21:11

ALNAJJAR


Yes, you can load the Flutter web library, only when it is called using Deferred/Lazily loading. Here I copy/paste from Dart documentation:

Lazily loading a library

Deferred loading (also called lazy loading) allows a web app to load a library on demand, if and when the library is needed. Here are some cases when you might use deferred loading:

To reduce a web app’s initial startup time.
To perform A/B testing—trying out alternative implementations of an algorithm, for example.
To load rarely used functionality, such as optional screens and dialogs.

And here an article related to this topic.

like image 38
I Made Mudita Avatar answered Nov 15 '22 19:11

I Made Mudita