Lazy Load Libraries in Dart

UPDATE: This article is now DEPRECATED, but the feature lives on! Dart now formally supports lazy loading (deferred) libraries. Learn more in the Deferred Loading in Dart article.

Dart is a statically analyzable language, and its tree-shaking compiler does a good job of eliminating dead code and producing a single, optimized application file. However, sometimes developers need to control when certain libraries are loaded and thus need to control which libraries are included in the main application file. To help, the dart2js compiler, which converts Dart code into JavaScript code, now supports lazy-loaded libraries.



Lazy Load

As an example, consider an application that has many different screens. Some screens are more obscure than others, and aren't required for the application to start. A developer should be able to say "I don't need these screens now, but pull them in when I do need them." This lazy-loading is a common deployment strategy for web apps, because small initial loads means faster application startup.

You can mark a library as "lazy", and the dart2js compiler will output a separate JavaScript file for that library. Note that dart2js still performs tree shaking (aka dead code elimination) across the entire app (technically, across the entire isolate). This means that only the functionality required from the lazy-loaded library will actually be compiled into the separate file.

The lazy-loaded library is still part of the application structure, and must exist and be available to dart2js when the program is compiled. This is not "dynamic loading", per se, because the application must statically import all libraries (lazy or not).

(Note: as of the time of this writing, dart2js emits at most one other JavaScript file. This restriction will be removed and you will be able to emit multiple files for a single application. Please track Dartbug 3940 to learn more.)

DeferredLibrary Example

The main application can mark a library with an @lazy metadata. Then, it declares an instance of DeferredLibrary that points to the outputted JavaScript file.

import 'dart:html';
import 'dart:async';

@lazy
import 'reverser.dart';

const lazy = const DeferredLibrary('reverser', uri: './part.js');

void main() {
  lazy.load().then((_) {
    print('library loaded');
    query("#sample_text_id")
      ..text = "Click me!"
      ..onClick.listen(reverseText);
  });
}

void reverseText(MouseEvent event) {
  query("#sample_text_id").text =
      reverse(query("#sample_text_id").text);
}

Notice how the library doesn't come into existence until after the Future from lazy.load() completes. Only then can you call into the library.

The runtime throws NoSuchMethodError if you try to access functionality from a library that it not yet loaded.

More to come

The lazy-load functionality of dart2js is just the beginning. In the future, you will be able to mark multiple libraries as "lazy", and really control how you deploy and load your web application.

Also, this functionality only currently works with dart2js. Please star Dartbug 10171 if you are interested in seeing the same lazy-loading for the VM and Dartium.

Please try this out, we look forward to your feedback!


(Photo Credit: Marcus Hansson licensed under cc)

Popular posts from this blog

The 29 Healthiest Foods on the Planet

Lists and arrays in Dart

Converting Array to List in Scala