Long story short, it is not a matter of which is better, it is a matter of how to use code splitting and lazy loading to get the best of both.
We will first understand what code splitting is all about, and its core benefit, then we will do the same for lazy loading. Then after that, get an understanding of how they work together to help you achieve maximum performance in your JavaScript web applications.
Code splitting is the process of splitting up a large file or module into smaller manageable chunks of code, which can be loaded on demand.
This makes it very easy to separate concerns in your JavaScript module for example, and with modules comes the benefit of easy manageability.
You may have seen these in your React project or Angular projects after you compile them, there are those chunks files. Yes, these are analogous to what defines code splitting.
This is the process of loading only what is needed when it is needed. That is basically it.
You can lazy load script files when you need them and now, some browsers support even lazy loading images. But the focus here is lazy loading code, and thus scripts.
This is important since you only get to initially load that which the current screen of your application needs.
In the past, web applications had to load all the script files, well, things have changed for the better – you only get what you ordered for.
Well, if you were to accomplish these two, you would have super fast loading times on your web application.
Even if they can be used in isolation, using code splitting for small sizes and lazy loading for on-demand availability of scripts will make your web application feel more perfomant.
So, use code splitting to reduce the size of your application module bundles and lazy loading to load the smaller chunks only when needed