Skip to content

Instantly share code, notes, and snippets.

@3rd-Eden
Created November 5, 2011 18:56
Show Gist options
  • Save 3rd-Eden/1341882 to your computer and use it in GitHub Desktop.
Save 3rd-Eden/1341882 to your computer and use it in GitHub Desktop.
custom script loader
(function (global) {
var _namespace = global.namespace
, namespace = {};
namespace.push = function push (fn) {
return fn && typeof fn === 'function' && fn(namespace);
};
if (_namespace && _namespace.length) {
var i = _namespace.length;
while (i--) namespace.push(_namespace[i]);
}
}(this))
(function (a, b, c, d, e, f){
for (d = c.length, f = a.getElementsByTagName(b)[0]; d--;) {
e = a.createElement(b);
e.src = c[d];
f.parentNode.insertBefore(e, f);
}
})(
document
, 'script'
, [
'http://cdn.example.com/core.js'
, 'http://cdn2.example.org/page.js'
]
)
('namespace' in this ? namespace : (namespace = [])).push(function push (namespace) {
});
@3rd-Eden
Copy link
Author

3rd-Eden commented Nov 5, 2011

Rolling your own script loader

So what is wrong with the current script loaders:

  • They contain code bloat because they are designed to be used in many different use cases. For script loading there isn't one size fits all. Every project or site has their own needs.
  • They are not optimizing for front-end performance, this is a must for me. I want the resources to be loaded as fast as possible without having to wait for a dependency to be loaded and continue with the rest of the resources.
  • They should be optimized for cross domain. Most static content is served from a different, cookie less domain / CDN.
  • They use user-agent sniffing or other sad techniques for loading, which might break in future browser updates.

So luckily I had the opportunity to design our code base from the ground up, so I knew I wanted to make it as fast and no-blocking as possible. My build system detects which scripts are depended on by different scripts and includes them in to a "core" file. I also assume that all widgets and page specific functionality will break if this is not included or available on the page when the script is executing.

@tblobaum
Copy link

tblobaum commented Nov 6, 2011

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment