[whatwg] Deferring javascript download and execution until after onload

Andy Davies dajdavies at gmail.com
Mon Dec 17 14:30:14 PST 2012

On 29 November 2012 04:01, Ian Hickson <ian at hixie.ch> wrote:

> On Mon, 17 Sep 2012, Andy Davies wrote:
> >
> > The script defer attribute allows us to defer JS until after
> > DOMContentLoaded (?) but it will still execute before onLoad
> Actually defer="" defers to just before DOMContentLoaded, but <script>
> elements with a src="" attribute that are inserted into the document
> dynamically will load between DOMContentLoaded and onload, so you can do
> all your important loading in the DOMContentLoaded handler.
> You can use this pretty easily:
>    function loadScript(url) {
>      var script = document.createElement('script');
>      script.src = url;
>      document.appendChild(script);
>    }
>    load('mylibrary.js');
>    load('myotherlibrary.js');
> This can be trivially extended to, e.g., add IDs and support the script
> being inserted by inline script in specific places:
>    function loadScript(url, id) {
>      var script = document.createElement('script');
>      script.src = url;
>      script.id = id;
>      var target = document.currentScript;
>      target.parentNode.insertBefore(script, target.nextSibling);
>    }
>    <!-- at the specific place you want this script -->
>    <script>
>      loadScript('mylibrary.js', 'mylib');
>    </script>

OK, so we have async and defer which will still block DOMContentLoaded and
to defer anything until after DOMContentLoaded developers have to resort to

That's a mess, even before we consider the hoops people like Facebook are
jumping through to avoid blocking problems (

Sites that want to implement CSP are going to lose the JS to load JS route
unless they allow inline scripts which probably defeats one of the reasons
they want to use CSP in the first place.

What we need are better ways of hinting to the browser what the priority of
the external JS is i.e. the current default behaviour, async, and defer
behaviours with options to defer until after DOMContentLoaded or onload.

Users shouldn't have to wait for Facebook, Google Plus, Twitter or A N
Other 3rd party script to execute before they can start interacting with a
page and we need to make it easy for developers to implement these scripts.


More information about the whatwg mailing list