Best way to avoid including stylesheets / external js more than once per page

I need to clean / save some old php site files. There are a number of basic php pages that include () other rule-based php files. Some of them include the following lines:

<link href="css/styles.css" rel="stylesheet" type="text/css"> <script language="javascript" src="js/functions.js"></script> 

Some time after creating a php page, these external files are included more than once on the same page.

This is not just a simple case of removing these external file links from php, because sometimes, when php is enabled, this is the only event.

Is there any check, either php or js, to avoid multiple external files appearing?

Thanks:)

+1
source share
5 answers

As a simple hack, add these CSS and JS files to the PHP file and put require_once in the PHP file. Thus, the file will be included only if it is not already included.

+2
source

As far as I know, there is no easy way to do this, you can rearrange the entire code base so that the server-side inclusion logic only occurs in the file, and not in the entire application.

If you enable caching and set the correct headers, I believe that when the external file is already cached, the browser will not try to reload if it requests the same file again.

0
source

You can write the import of a specific file (for example, "styles.css" in the above example) in a variable (for example, $ styles_loaded = true or better, $ LoadedImports ['styles'] = true) and check in all includes the value this variable. This way you will know whether to import a specific file or not. Or refactoring suggested by andreas.

0
source

This can be done using PHP and defining the constants when you include the file, if you always load them only in PHP or, possibly, in 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>'; } } 

Then you can simply call it like this: javascript_load ('/jquery.js', 'jquery'); which will output the correct tag for the js file.

You can do something similar with css, maybe

0
source

Dynamic JS loading using http://api.jquery.com/jQuery.getScript/ or a similar function from other libraries.

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

0
source

All Articles