开发者

PHP/APACHE: can i auto_prepend to a .js file?

开发者 https://www.devze.com 2023-01-11 05:24 出处:网络
I\'d like to auto_prepend_file all my js files with:开发者_开发知识库 var SITE_ROOT = \'http://www.mydomain.com\';

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?!!!


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>


I think you are searching for mod_layout.

0

精彩评论

暂无评论...
验证码 换一张
取 消