Degrading script tags for fun and profit
Written by on August 29th, 2008 in Uncategorized.
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:
-
-
<script src=“some-lib.js”>
-
var foo = use_some_lib();
-
foo.do.stuff();
-
</script>
-
To make this all work, John shows us a jquery aware version that detects loading and such:
-
-
-
(function(){
-
var scripts = document.getElementsByTagName(“script”);
-
var curScript = scripts[ scripts.length - 1 ];
-
-
if ( curScript.executed )
-
return;
-
-
// … jQuery …
-
-
curScript.executed = true;
-
var script = curScript.innerHTML;
-
if ( script ) {
-
jQuery(document).ready(function(){
-
jQuery.globalEval( script );
-
});
-
}
-
})();
-
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).
Source: Ajaxian » Front Page
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/378073731/degrading-script-tags-for-fun-and-profit