May 25

How to download scripts and stylesheets

Tag: ToolkitAndrea Ercolino @ 20:59:12

With the help of some basic DOM manipulation and no AJAX at all it is possible to write some useful functions for downloading scripts and stylesheets after the page has been loaded.

load_javascript = function( uri ) {
	if( document.createElement ) {
		var e = document.createElement( "script" );
		e.type = "text/javascript";
		e.src = uri;
		document.getElementsByTagName( "head" )[0].appendChild( e );
	}
};

load_javascript_inline = function( sourceCode ) {
	if( document.createElement ) {
		var e = document.createElement( "script" );
		e.type = "text/javascript";
		e.text = sourceCode;
		document.getElementsByTagName( "head" )[0].appendChild( e );
	}
};

load_stylesheet = function( uri ) {
	if( document.createElement ) {
		var e = document.createElement( "link" );
		e.rel = "stylesheet";
		e.type = "text/css";
		e.href = uri;
		document.getElementsByTagName( "head" )[0].appendChild( e );
	}
};

load_stylesheet_inline = function( sourceCode ) {
	if( document.createElement ) {
		var e = document.createElement( "style" );
		e.type = "text/css";
		if( e.styleSheet ) { // IE
			e.styleSheet.cssText = sourceCode;
		} 
		else {
			var t = document.createTextNode( sourceCode );
			e.appendChild( t );
		}
		document.getElementsByTagName( "head" )[0].appendChild( e );
	}
};

Leave a Reply