[whatwg] Deferring javascript download and execution until after onload

Jonas Sicking jonas at sicking.cc
Mon Sep 17 23:54:19 PDT 2012

On Mon, Sep 17, 2012 at 4:19 AM, Andy Davies <dajdavies at gmail.com> wrote:
> The script defer attribute allows us to defer JS until after
> DOMContentLoaded (?) but it will still execute before onLoad
> Sometimes there's a quite a bit of content on a page that could be
> deferred until after onLoad, for example suplemental content such as
> social media buttons, feedback forms etc. where they really don't make
> much sense until the page hase loaded.
> Currently patterns like the code below are being used to implement
> this type of behaviour but has any thought been given to being able to
> specify as part of the script element that the script could be
> deferred until after onLoad?
> <script>
> (function(w, d, s) {
>   function go(){
>     var js, fjs = d.getElementsByTagName(s)[0], load = function(url, id) {
>           if (d.getElementById(id)) {return;}
>           js = d.createElement(s); js.src = url; js.id = id;
>           fjs.parentNode.insertBefore(js, fjs);
>         };
>     load('//connect.facebook.net/en_US/all.js#appId=272697932759946&xfbml=1',
> 'fbjssdk');
>     load('https://apis.google.com/js/plusone.js', 'gplus1js');
>     load('//platform.twitter.com/widgets.js', 'tweetjs');
>   }
>   if (w.addEventListener) { w.addEventListener("load", go, false); }
>   else if (w.attachEvent) { w.attachEvent("onload",go); }
> }(window, document, 'script'));
> </script>
> Script was borrowed from
> http://www.aaronpeters.nl/blog/why-loading-third-party-scripts-async-is-not-good-enough

There has been discussions about implementing a "noexec" attribute on
<script> which would just load the script but instead of evaluating it
as soon as it's available, simply fire the "load" event. There would
also be an additional .execute() function on the script which would
permit executing the script after it has been loaded.

This has mostly been discussed in a performance context where people
has expressed interest in loading scripts, while only waiting to
execute it until needed in order to avoid the costs involved in
parsing and executing the script.

So far Hixie hasn't been interested in putting this into the spec
though, due to, as I understand it, not being convinced that it's
needed from a performance point of view.

I'd personally be interested to see it implemented since people
clearly do load scripts dynamically and it would seem common for such
scripts to have dependencies on each other, which means that you have
to be able to execute them in a certain order.

/ Jonas

More information about the whatwg mailing list