3 ms·
On modern browsers you don't even need this method. A simple <script src="//blablabla.bla/bla.js" async></script> will get you the same effect with the a
by bluesmoon 10y ago
On modern browsers you don't even need this method. A simple
<script src="//blablabla.bla/bla.js" async></script>
will get you the same effect with the added advantage that the browser's lookahead parser can detect the script and start downloading it even before the DOM has been constructed.
The problem with both methods, however, is that they will still block the onload event from firing until after the script has finished downloading.
There are only two ways to get around that.
The first is silly in how obvious it is... if you load a script after onload has happened, then it cannot block onload. This has the downside of not using parallelism.
The second method is to load the script in an iframe whose onload event has already fired. It's a bit more involved, and absolutely requires the use of document.write inside the iframe. I've documented the method here, and it works on all browsers: http://www.lognormal.com/blog/2012/12/12/the-script-loader-pattern/ http://www.lognormal.com/blog/2012/12/12/the-script-loader-p...
- taeric 10y agoI'm not sure I understand your point. Isn't the goal of this technique to add somewhat dynamic scripts to the page? Specifically, the page includes "foo" but it basically just bootstraps "bar" and "baz." That is, if you already know the script you want to load, yes. Just load it. This is for the case where you are loading a script that will, in turn, decide what scripts need loading.
- acdha 10y agoI think that's confused because a lot of people read a blog post from a decade ago about a dynamic script loader and IE6, and have retained the mistaken belief that a script loader is necessary for performance. I regularly encounter websites which wait for a loader script to initialize before starting to request a static set of JS+CSS files, where a simple <script defer> or <script async> would have been both easier and considerably faster. (That's not to say that dynamic loading isn't a useful tool, only that a non-trivial number of web developers have fossilized impressions of the modern web performance environment)
- bluesmoon 10y agoperhaps what we really need is a capabilities attribute on all `script` nodes, so the browser can determine if it needs to be loaded or not. For example: <script src="usertiming-polyfill.js" provides="usertiming"></script> If the browser supports user timing, it does not load the script. If the browser does not support user timing (or does not support the `provides` attribute), it loads the script.