Search This Blog

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.

Popular posts from this blog

Now, this has to have a built-in somewhere in Scala , because it just seems too common. So, how to convert an Array to a List in Scala? Why do I need this? I needed to drop to Java for some functionality, which in this case returns an Array. I wanted to get that Array into a List to practice my functional programming skillz. **Update**: I figured out how to convert Arrays to Lists the Scala way. Turns out it's a piece of cake. val myList = List.fromArray(Array("one", "two", "three")) or val myList = Array("one","two","three").elements.toList The call to elements returns an Iterator , and from there you can convert to a List via toList . Nice. Because my first version wasn't actually tail recursive, what follows is a true tail recursive solution, if I were to implement this by hand. The above, built in mechanism is much better, though. object ArrayUtil { def toList[a](array: Array[a]): List[a] = { d

In which I port a snazzy little JavaScript audio web app to Dart , discover a bug, and high-five type annotations. Here's what I learned. [As it says in the header of this blog, I'm a seasoned Dart developer. However, I certainly don't write Dart every day (I wish!). Don't interpret this post as "Hi, I'm new to Dart". Instead, interpret this post as "I'm applying what I've been documenting."] This post analyzes two versions of the same app, both the original (JavaScript) version and the Dart version. The original version is a proxy for any small JavaScript app, there's nothing particularly special about the original version, which is why it made for a good example. This post discusses the differences between the two implementations: file organization, dependencies and modules, shims, classes, type annotations, event handling, calling multiple methods, asynchronous programming, animation, and interop with JavaScript libraries. F

In which the virtues of automated mechanical arboreal pruning are extolled over quaint manual labor, as applied to web development build processes. The setup Ever notice how the primary bit of marketing for many traditional web programming libraries is their download size? Why is that? Check this out: Why does size matter so much for these libraries? Your first instinct is probably, "because the more bytes you shuttle across the wire, the slower the app starts up." Yes, this is true. I'd also say you're wrong. The primary reason that size matters for these libraries is because traditional web development has no intelligent or automated way to prune unused code so you can ship only the code that is used over the wire. The web is full of links, yet web dev has no linker The web development workflow is missing a linking step. A linker's job is to combine distinct project files into a single executable. A smart linker will only incl