Best way to avoid including stylesheets/external j

2019-08-03 08:18发布

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 checking, either by php or js to avoid multiple occurrences of external files?

Thanks :)

5条回答
We Are One
2楼-- · 2019-08-03 08:41

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.

查看更多
聊天终结者
3楼-- · 2019-08-03 08:43

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

查看更多
甜甜的少女心
4楼-- · 2019-08-03 08:56

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.

查看更多
爷、活的狠高调
5楼-- · 2019-08-03 09:06

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.

查看更多
老娘就宠你
6楼-- · 2019-08-03 09:08

Dynamically Load JS using http://api.jquery.com/jQuery.getScript/ or similar feature from other libraries.

Define a variable $MY_LIBRARY_IDENTIFIER in js If already defined skip else load the js

查看更多
登录 后发表回答