Use wildcard in src attribute of <script> tag?

El Ronnoco picture El Ronnoco · Feb 17, 2011 · Viewed 12.5k times · Source

Ok, stupid question and I don't think it's possible but, I have this markup at the top of my .aspx page...

<%--Third Party Libraries, Plugins, Extensions --%>
<script src="Libraries/Raphael/Raphael.js" type="text/javascript"></script>
<script src="AutoComplete/jquery.autocomplete.js" type="text/javascript"></script>    
<script src="Libraries/jQuery/1.4.2/jquery.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.core.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.widget.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.mouse.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.draggable.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.droppable.js" type="text/javascript"></script>    

Wouldn't it be nice if I could replace that with this...

<%--Third Party Libraries, Plugins, Extensions --%>
<script src="Libraries/Raphael/Raphael.js" type="text/javascript"></script>
<script src="AutoComplete/jquery.autocomplete.js" type="text/javascript"></script>    
<script src="Libraries/jQuery/1.4.2/jquery.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.*.js" type="text/javascript"></script>

ie use the * as wildcard.

Obviously as this is JS I could just throw all those scripts into one big script and load that but I don't really fancy doing that.

Anyone else have a technique for tidying up masses of script refs? Or do we just live with it?

Answer

xzyfer picture xzyfer · Feb 17, 2011

As far as I know this is not possible, simply because, the browser would need to know exactly what files to request.

The browser would essentially have to brute force your server with requests hoping to get lucky.

I'd suggest using Google's closure compiler to merge all similar, if not all, javascript files into a single file. It will be slightly large, but would cut down on http request.

With some profiling you could find a balance between which files are needed most commonly and speed.

UPDATE (from comments)

I'm generally reluctant to offer adding a new javascript library to solve the issue of too many javascript libraries :) Plus this just seemed like the more straight forward solution. Current we use the Google closure API to compress and merge all our javascript and CSS and build time with ANT. Works a charm. This can also be done to some extent direct with apache2 virtual host/htaccess (see html5boilerplate.com) for examples and limitations