简体   繁体   中英

What can I do if my Backbone main.js is too big?

I use require.js (AMD) and optimize it into one final javascript file (main.js)

My main.js is half a megabyte, and it will continue to increase.

The problem is: when the client loads my backbone app, they must first download the entire half megabyte file before they can browse the site. (the router is included inside the file)

Oftentimes this can take 3 seconds before the initial load.

What can I do?

Split your code up into the following categories and use separate requirejs modules for each.

  1. Core code required to get the initial app displayed
    • Most of your modules that are heavily used through your app can go here
  2. Secondary code that is OK to arrive in a subsequent request via AMD
    • things like animation helpers, stuff that only appears on click, etc
  3. Any modules that are only needed in the corners of your app
    • specialty error handlers
    • edge case logic
    • paths most users don't take through your app (like a refund module in a e-commerce app)

That way with a single, hopefully reasonably sized request, your app is up and running. A second request takes another second or so to get you 98% loaded, and the last 2% trickles in on-demand if a given user needs it.

Requirejs has facilities for doing this via the config file. It just takes some forethought and testing to find the right places to draw the dividing lines for your specific application.

General tips: consider fewer large third party dependencies. Consider a separate bundle for administrators if you have different user roles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM