I've having to clean up/maintain some old php site files. There are a number of main php pages which include() other php files based on rules. A number of these includes have lines such as below in them:
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script language="javascript" src="js/functions.js"></script>
Some of the time after the php page has been built, these external files are included more than once in the same page.
It's not just a simple case of removing these external file links from the php includes, as sometimes where the php include is placed, it is the only occurrence.
Is there some kind of ch开发者_如何学Pythonecking, either by php or js to avoid multiple occurrences of external files?
Thanks :)
As an easy hack, add those CSS and JS files into a PHP file, and put a require_once to the PHP file. That way the file will only be included if it hasn't been included yet.
As far as I know, there's no easy way of doing this, you could re-factor the whole code base such that the server side inclusion logic only happens in a file and not throughout the application.
If you turn on caching and set the correct headers, I believe once an external file is already cached, the browser won't attempt to redownload in the case of subsequent request of the same file.
You could record the import of a certain file (such as "styles.css" in your example above) in a variable (e.g. $styles_loaded = true or better yet, $LoadedImports['styles'] = true) and check in all includes for the value of this variable. That way you'll know whether to import a certain file or not. Or refactor as andreas suggested.
You could do this using PHP and defining Constants when you include the file, if you're going to always only load them in PHP, or perhaps javascript.
This may work as a PHP Solution:
function checkJSLoad($var){
if(!defined($var)){
define($var, 1);
return false;
} else {
return true;
}
}
function javascriptLoad($location, $defined = ''){
if(!$defined) { $defined = 'JS_' . $location; }
if( !checkJSLoad($defined) ){
return '<script type="text/javascript" src="'.$location.'"></script>';
}
}
You could then just call it like so: javascript_load('/jquery.js','jquery'); which would echo out the correct tag for the js file.
You could do something similar with css perhaps
精彩评论