Specifing an alternate dart.js file to use

Dart applications fallback to JavaScript in browsers that don’t support the dart VM. This funcationality is handled by a very small JS script provided by the Dart project. The script is located in the browser package. This works by taking the Dart file name and appending .js on to the end of it, which is the default naming convention for the JS file produced by the cross compiler Dart2js. For example, the file:




But what if that naming convention doesn’t work for you? This could happen when deploying to a file server or CDN, which may change the file or path naming.

Here is a small replacement for the script that ships with the Dart project. This one allows you to specify the js file using a data arrtribute like so:

<script type="application/dart" src="app.dart" data-js-src="other.dart.js"></script>

This implementation falls back to the default solution of simply appending ‘.js’ on to the file if one is not specified. Here is the full snippet for this:

    // if dart not supported
    if (navigator.userAgent.indexOf('(Dart)') === -1) {
        var scripts = document.getElementsByTagName("script");
        var length = scripts.length;

        for (var i = 0; i < length; ++i) {
            var s = scripts[i];
            if (s.type == "application/dart") {
                var src = s.getAttribute("data-js-src");
                if (!src && s.src && s.src != '') {
                    // Remap foo.dart to foo.dart.js.
                    src = s.src.replace(/\.dart(?=\?|$)/, '.dart.js');
                if(!src) {

                var script = document.createElement('script');
                script.src = src;
                var parent = s.parentNode;
                document.currentScript = script;
                parent.replaceChild(script, s);


Dart, JS

You can contact me on Twitter.


Browse All >