views:

55

answers:

2

This sounds a little obscure, but... Is there a technique in Jquery (or just straight javascript) to step thru all the external CSS and JS file references in an HTML file and replace the references with the contents of the files.

So instead of:

<link rel='stylesheet' id='style-css'  href='http://domain.com/style.css' type='text/css' media='all' />    
<script type='text/javascript' src='http://domain.com/js/domain.js'&gt;&lt;/script&gt;

..it takes all the stuff from those files and sticks it into the rendering html to make one big html doc...?

<head>
...
<style type="text/css">
hr {color:sienna}
p {margin-left:20px}
body {background-image:url("images/back40.gif")}
.etc {color:red}
.etc {color:red}
.etc {color:red}
</style>

<script type="text/javascript">
function message()
{
alert("This is an alert");
}
etc
etc
</script>
</head>
<body>
...
</body>
+2  A: 

Add this script..

$("script").each(function() { 
    var script = $(this);
    script.load(script.attr("src"));
    script.removeAttr("src");
});
$("link[rel='stylesheet']").each(function() { 
    var link = $(this);
    link.after("<style type='text/css'></style>").next().load(link.attr("href"));
    link.remove();
});

..and you can test it with..

alert($("head").html());

..when it's all done.

(And I don't see any reason in doing this ;)

Sverre Ølnes
A: 

The only place I can imagine that makes sense is if you run Javascript on the server, using Rhino or similar.

You can do as Sverre suggests and load the files yourself from the browser instead of letting the browser do it, but I can't see any scenario where that would be useful - you have the same number of background requests and end up with the same result, so the only thing you gain is extra work for yourself and probably some extra delay in rendering the page. Or do I misunderstand your goal?

On the server, on the other hand, it can make sense, as the browser can save a load of requests by getting all the external resources in the same document. Is this what you want to achieve?

j-g-faustus
The last is better achieved by concatenating multiple script and css files into two files which can than be cached. But I don't think that is what the OP is after.
Joel Potter