views:

40

answers:

2

I'd like to auto_prepend_file all my js files with:

var SITE_ROOT = 'http://www.mydomain.com';

Can this be done in .htaccess like it can for php files, if so, how?!!!

A: 

Hello, I think you are searching for mod_layout.

greg0ire
+1  A: 

You could accomplish what you're seeking with a mod_rewrite rule and a small php file:

js_wrapper.php:

<?php
// Open a javascript file provided by ?file=somefile.js and to prepend some content

$file = $_GET['file'];

// Checks that the file exists on the system and that it ends in '.js'
// The RewriteCond's do the same thing, but this prevents direct 
// calls to js_wrapper.php as well
if(!is_file("./" . $file) OR !preg_match('#\.js$#', $file)) {
    // 404
    header("HTTP/1.0 404 Not Found");
    print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> 
<html><head> 
<title>404 Not Found</title> 
</head><body> 
<h1>Not Found</h1> 
<p>The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found on this server.</p> 
<hr> 
</body></html>';

}

header("Content-type: text/javascript");

// Begin prepended content
?>
// Auto-prepended by js_wrapper
var SITE_ROOT = 'http://www.mydomain.com';
// End auto-prepend

<?php 
// Output the original file
echo file_get_contents($file);
?>

.htaccess:

# Pass all requests to js/some/script.js through js_wrapper.php?file=js/some/script.js
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} \.js$
RewriteRule ^js/(.*)$  js_wrapper.php?file=js/$1  [L,NC,QSA]

You should modify the RewriteRule directive to reflect a different path if your scripts aren't under a folder named 'js'.

Alternatively...

Since in your example you're merely defining a variable at the start, if this is all you're looking to do, you should be able to accomplish this by using a <script> block in your <head> block of the page including the js scripts. The js scripts will be able to access any variables you define there. This is much simpler, easier to maintain, uses less 'magic' (people reading the rendered html source and js won't understand where the prepended data is coming from unless they read .htaccess), and is how I would probably do what you're trying to accomplish.

<head>
... stuff ...
    <script type="text/javascript">
        var SITE_ROOT = 'http://www.example.com';
    </script>
    <script type="text/javascript" src="/js/some_script.js"></script> 
    <script type="text/javascript" src="/js/some_other_script.js"></script> 
... stuff ...
</head>
Brent C
this looks cool, are there any drawbacks? (performance?)
Haroldo
Well, certainly the server is doing more to serve these requests instead of a direct link to non-processed file, but the performance hit should pretty negligible.
Brent C
thanks brent, this looks like an excellent solution. Also thanks for writing such a well explained answer
Haroldo