Skip to content

Instantly share code, notes, and snippets.

@demoive
Last active December 11, 2015 06:59
Show Gist options
  • Save demoive/4563398 to your computer and use it in GitHub Desktop.
Save demoive/4563398 to your computer and use it in GitHub Desktop.
CDNJS Combo Loader

CDNJS Combo Loader

A proposal for CDNJS to support combined requests allowing their resources to be served in a reduced number of HTTP connections (inspiration by YUI's combo loading service).

[UPDATE: This has been offically declined in issue 791 for CDNJS. I'm keeping the proposal in this gist for posterity].

Example

Instead of four separate requests:

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.3/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.9/backbone-min.js"></script>

... developers could do the following and utilise a single request:

<script src="//cdn1js.cloudflare.com
?ajax/libs/jquery/1.8.3/jquery.min.js
&ajax/libs/mustache.js/0.7.0/mustache.min.js
&ajax/libs/underscore.js/1.4.3/underscore-min.js
&ajax/libs/backbone.js/0.9.9/backbone-min.js"></script>

Discussion

Indeed, this would diversify the number of "unique" resources, making it less likely for browsers to cache common requests. But since this would be an option in addition to the existing individual file serving, it doesn't really hurt to have it! In my personal opinion, the pros outweigh the cons:

Pros

  • Reduces latency by serving fewer, individual requests
  • Strengthens CDNJS ability to used in production environments

Cons

  • Browsers are less likely to encounter cache collisions
  • Could be more difficult to maintain source code (especially for novice developers)

Specs

  • Files are concatenated in the order they are listed. This can be used to manage dependencies.
  • If any file fails to load, the entire request fails. The idea here being that the scripts you are loading onto your page is assumed to be required for it to run. If one isn't available, then tough luck. This also follows the idea of dependencies and developers could combine different groups of dependencies.

Potential base URLs

//cdnjs1.cloudflare.com?
//cdn1js.cloudflare.com?
//cdnjs.cloudflare.com/1?
//cdnjs.cloudflare.com/combo?

Psuedo-code-ish code for serving libraries

var MAX_URL_LENGTH = 1024,
  SEPARATOR = '&',
	resources = [],
	concat = '';

if (location.href.length > MAX_URL_LENGTH) {
	// return either nothing or an error
} else {
	resources = location.search.split(comboSep)

	resources.forEach(function (resource) {
		concat += read(location.origin + '/' + resource);
	});

	serve(concat);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment