[whatwg] Media aware JS loading

Arguably, the biggest problem in responsive Web design today is the fact
that many resource loading mechanisms are media query agnostic, and
download resources upfront regardless of whether they will be used or not.

One of the biggest resources in question (right after images) is external
JavaScript. JavaScript also has secondary performance effects, beside its
download size, since parsing and running it are also time (& battery)
consuming operations.

Currently authors that want their scripts to load only under certain
viewport sizes are forced to use JS based script loaders, which have the
side-effect of preventing these scripts from being parsed out by the
preloader.

I believe that an HTML based solution would be a better fit, will be easier
to use by authors, and will enable preloaders to do their job and preload
these scripts.

Common use-cases for avoiding the load of JS based components based on
layout are:

* JS based maps, which don't fit in a narrow layout
* Social widgets, which don't fit in a narrow layout
* Mobile/desktop oriented UI libraries
* Ad placements

I was thinking along the lines of adding a `media` attribute to the
`<script>` element.
Doing that raises several interesting questions:

* What will be the execution order of these scripts if the media conditions
of the page change?
* Should `media` be permitted for scripts with no `defer`/`async`
attributes, that may contain document.write directives?
* Should scripts re-run if media conditions changed more than once (e.g.
their `media` intially matched conditions, then stopped, then matched again)
* Should events handlers that were registered by scripts which media no
longer matches run?

I believe that mandating `async` (at least as a first step) will enable
avoiding the running-order problems, with authors being obliged to avoid
any dependencies between `media` scripts and other (`media` or non-`media`)
scripts.

Regarding the script re-run and event handler scenarios, I'm not sure what
the right answer should be.

I'd highly appreciate any thoughts on the subject.

Yoav

Received on Thursday, 16 May 2013 13:23:25 UTC