On Tue, 09 Jul 2013 20:39:45 +0100, Ian Hickson <i...@hixie.ch> wrote:

Would something like this, based on proposals from a variety of people in
the past, work for your needs?

1. Add a "dependencies" attribute to <script> that can point to other
   scripts to indicate that execution of this script should be delayed
   until all other scripts that are (a) earlier in the tree order and (b)
   identified by this attribute have executed.

     <script id="jquery" src="jquery.js" async></script>
     <script id="shims" src="shims.js" async></script>
<script dependencies="shims jquery" src="myscript.js" async></script>

On a basic level it's similar to JS async module definition pattern (https://github.com/amdjs/amdjs-api/wiki/AMD), which is good, but may be insufficient.

require.js (AMD implementation) has useful concept of loader "plugins" for dependencies (https://github.com/millermedeiros/requirejs-plugins). A plugin is basically a function that is told to load a path and calls callback when it's done.

It solves two problems:

1. not all dependencies are JS files, e.g. authors use plugins to load template files, JSON, images, etc.

    <script dependencies="load_template('view.hbs')" src="view.js">
    <script>
        function load_template(url, callback) {
fetch(url).then(callback); // in require.js result is directly passed to the module.
        }
    </script>

2. not all dependencies are usefully satisfied immediately after their JS file is loaded, e.g. some libraries may need asynchronous initialization. In require.js it's possible to wrap initialization in a plugin that will wait until it's done, so modules dependent on it can start using initialized library right away.

    <script id="load-library" src="library.js" />
    <script dependencies="load-library">
        function library_initialized(callback) {
            $library.on('ready', callback)
        }
    </script>
    <script dependencies="library_initialized()" src="use-it-now.js"/>


Another common kind of dependency scripts have is presence of certain element in the DOM, e.g. `dropdown-menu.js` may require `<nav id="menu">` to be in the document _and_ have its content fully parsed before the script can run.

So, could <script dependencies> point to non-<script> elements?

<script dependencies="menu" src="dropdown-menu.js"/>
<nav id="menu">
<!-- script not run yet -->
<ul>...</ul>
</nav>
<!-- script run at this point -->

It would be nice if the browser also deferred rendering of the element until scripts that depend on it are run to avoid "Flash of Unbehaviored Content" (e.g. elements listed in dependencies have display:none until scripts are run).

--
regards, Kornel

Reply via email to