Kernel's solution is probably what you are looking for
you can either use <script src="http://so.me/file.js" defer></script>
or <script src="http://so.me/file.js" async></script>
- defer : load in parallel and execute in order
- supported in almost all browsers including older versions of IE ..however execution order is not always respected even though it should be..
- async: load in parallel and execute as soon as possible
- supported in almost all browsers browsers except IE where support was only added in IE10
Landon's solution is the same as using async
, except you are controlling things programmatically.
...that said, almost all modern browsers will default to the defer method, whether you specify something or not. Try loading a bunch of scripts in a classic manner in FF or Chrome while looking at the waterfall chart in their developer tools (or Fiddler), and you'll see that they load everything in parallel even though you didn't even ask them to :)
Refined solution (should work in any browser):
<html>
<head></head>
<body>
<script>
window.onload = function() {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://so.me/file.js";
document.getElementsByTagName("head")[0].appendChild(s);
}
</script>
</body>
</html>
Then again if you're willing to do this, you can just as well stick your scripts at the end of your document right before </body>
.
Anything you stick in your <head>
or before </body>
will cause rendering to halt, but that doesn't mean it's a problem ..a page is rendered from top to bottom, so once you get to </body>
even if onload
hasn't fired yet, your page is already visible to the end user.