Friday, August 29th, 2008

Degrading script tags for fun and profit

Category: JavaScript, jQuery

John Resig posted on degrading script tags and adding functionality to <script> so you can add a src attribute and a body of code that will be executed one the external script loaded error free:


  1. <script src="some-lib.js">
  2.   var foo = use_some_lib();
  4. </script>

To make this all work, John shows us a jquery aware version that detects loading and such:


  1. (function(){
  2. var scripts = document.getElementsByTagName("script");
  3. var curScript = scripts[ scripts.length - 1 ];
  5. if ( curScript.executed )
  6.   return;
  8. // ... jQuery ...
  10. curScript.executed = true;
  11. var script = curScript.innerHTML;
  12. if ( script ) {
  13.   jQuery(document).ready(function(){
  14.     jQuery.globalEval( script );
  15.   });
  16. }
  17. })();

Where this kicks in, is more than just saving a script code block. Steve Souders has been researching different ways to tie blocks of code to scripts and having the optimal ordering for performance. We can tie this learning to John’s work, and the developer can choose what they want to do (e.g. when loading don’t have the icon moving etc etc).

Posted by Dion Almaer at 8:26 am

3 rating from 21 votes


Comments feed TrackBack URI

Hmm, I guess I’m a bit too concerned with some unforeseen issues with browser vendors to like this too much:

First, this is invalid HTML according to the specs:

Second, HTML5 offers the defer, and async attributes

Third, shouldn’t we as good web developers have all our scripts in external files anyway?

Also, wouldn’t the use of “curScript.innerHTML;” run into to trouble with inline tag strings?

Comment by TNO — August 29, 2008

this is neat trick. but i think it’d be more useful as a technique to execute code if the src’d script fails to load rather than post execute init code, but only if it was adopted into the spec.

Comment by davey — August 29, 2008

“Open Web” does not need to break standards, sure as a proposal for the *NEXT* standard of HTML this _might_ be a good suggestion, but breaking them…?
I though that was the job of the proprietary, activex2.0 RIA vendors…
Also the gains from this compared to the loss are very questionable…

Comment by ThomasHansen — August 31, 2008

Leave a comment

You must be logged in to post a comment.