Wondering how to reach a css file like this one from css-tricks.com
http://cdn.css-tricks.com/wp-content/themes/CSS-Tricks-9/style.css?v=9.5
Not sure if he is using php to accomplish this or not. I've been reading countless articles with no luck.
Also, is it something automated that spits out the version number after the .css? Been seeing it around and wondered how to achieve a clean css file.
Any help is appreciated! Thanks.
It's simple enough to use an editor with Search/Replace and strip out all the unnecessary spaces. For instance, when I write CSS I only use spaces to separate keywords - I use newlines and tabs to format it legibly. So I could just replace all tabs and newlines with the empty string and the result is "minified" CSS like the one above.
The version number is a fairly common cache trick. It doesn't affect anything server-side, but the browser sees it as a new file, and caches it as such. This makes it easy to purge the cache of all users when an update is made. Personally, though, I use a PHP function to append "?t=".filemtime($file) (in other words, the timestamp that the file was modified) automatically, which saves me the trouble of manually updating version numbers.
Here is the exact code I use to automatically append modification time to JS and CSS files:
<?php
ob_start(function($data) {
chdir($_SERVER['DOCUMENT_ROOT']);
return preg_replace_callback(
"(/(?:js|css)/.*?\.(?:js|css))",
// all the relevant files are in /js and /css folders of the root
function($m) {
if( file_exists(substr($m[0],1)))
return $m[0]."?t=".filemtime(substr($m[0],1));
else return $m[0];
},
$data
);
});
?>
I would avoid to do it manually because you may corrupt your css.
There are good tools available which will solve such problems for you without to be tricky.
An excellent solution is Assetic which is an assets manager and allow you to filter (minify, compress) using various tools (yuicompressor, google closure, etc..).
It is currently bundle by default with Symfony2 but may be used standalone in any PHP Project.
I've successfully implemented it in a Zend Framework project.
Related
This might be my mistake somewhere, but anyway, I am using the fat free framework which has an inbuilt function to minify multiple css/js into a single file, and I thought that this would be good for optimization, but it turns out the opposite. If I keep the js files separately(and they are at the end of my html), the total size if added, comes to around 364kb, and seems to load in parallel within 1.5 secs. If I try to load the combined version however, the single file size becomes around 343kb, but takes around 10secs to load.
My minifying logic is a bit different though. First in the template I call a function to load the files:
<script type="text/javascript" src="{{ #BM->minify('js','js/',array(
'vendor/jQui/jquery-ui-1.10.4.custom.min.js',
'vendor/datatables/jquery.dataTables.min.js',
'vendor/bootstrap.min.js',
'vendor/smartmenus-0.9.5/jquery.smartmenus.min.js',
'vendor/smartmenus-0.9.5/addons/bootstrap/jquery.smartmenus.bootstrap.min.js',
'vendor/smartmenus-0.9.5/addons/keyboard/jquery.smartmenus.keyboard.min.js',
'plugins.js',
'main.js'
)) }}"></script>
The function sets the appropriate session variables and returns a path.
public function minify($type='',$folderpath='css/',$files=array()){
$filepaths = implode(",",$files);
$this->f3->set('SESSION.UI_'.$type,$this->themeRelFolder().'/'.$folderpath);
$this->f3->set('SESSION.ReplaceThemePath_'.$type,$this->themeRelFolder());
$this->f3->set('SESSION.m_'.$type,$filepaths);
return($this->f3->get('BASE').'/minify/'.$type);
}
The path maps to a controller which calls the minify method and spits out the actual minified content.
public function index($f3, $params) {
$f3->set('UI',$f3->get('SESSION.UI_'.$params['type']));
if($params['type']=='css'){
echo str_replace("<<themePath>>","../".$f3->get('SESSION.ReplaceThemePath_'.$params['type'])."/",\Web::instance()->minify($f3->get('SESSION.m_'.$params['type'])));
}else
{
echo \Web::instance()->minify($f3->get('SESSION.m_'.$params['type']));
}
}
I did it this way so that I can minify as many files as the template needed, and also be able to maintain file paths no matter what folder nesting structure inside a theme.
What am I doing wrong?
PS: I am testing this on my local wamp setup, not an actual server, so the load times are obviously different than a actual web server.
Seems like the engine is re-minifying every time. I'll bet you just need to setup caching - http://fatfreeframework.com/web#minify :
To get maximum performance, you can enable the F3 system caching and
F3 will use it to save/retrieve file(s) to minify and to save the
combined output as well. You can have a look at the Cache Engine User
Guide for more details.
http://fatfreeframework.com/quick-reference#cache :
Cache backend. F3 can handle Memcache module, APC, WinCache, XCache
and a filesystem-based cache.
For example: if you'd like to use the memcache module, a configuration
string is required, e.g. $f3->set('CACHE','memcache=localhost') (port
11211 by default) or $f3->set('CACHE','memcache=192.168.72.72:11212').
You're making it minify those files on the fly every single time a page is loaded. This, obviously, takes time.
Consider minifying once, then just linking to that one file.
Good morning,
I'm creating my own framework to use in my PHP projects, and I was thinking of some way that I could add .CSS files in the header part of the page, and .JS files and scripts in the footer (keeping HTML clean and valid), but - all this dynamically.
I mean, for example, imagine I have the following structure:
index.php
components
component1
component1.php
component1.js
component1.css
I would like to include each file I need dynamically in index.php for example, keeping the code clean.
And for example, imagine that I insert JS directly in component1.php, is it possible to dynamically add it to component1.js (without human job, to save time in future)
Thanks.
One possible way of doing it would be to represent your entire template/view/whatever-you-want-to-call-it as an object:
class View {
// ...
}
The index.php file could determine which component(s) to use, create them, and then poll them for any required CSS/JS files:
$view = new View();
foreach ($components as $component) {
$cmp = new $component();
$view->addCss($cmp->getCss());
$view->addJs($cmp->getJs());
}
Once everything has been included and such, then index.php can just render the entire thing:
$view->render();
Obviously this is just an example, and your syntax will vary, but hopefully you get the idea.
Edit: You could also make the logic a little more brief by simply adding components to the view directly, and have the view's internal logic handle polling/adding the CSS/JS, rather than index.php. Of course, it really depends on what a "component" is supposed to be in your framework, so I'll leave that up to you to decide.
A very simple example of how to include your js and css assets at the top, before you start outputting anything:
// somewhere in the beginning, before html output
$js = array();
$css = array();
$css[] = 'all_pages.css';
$js[] = 'all_pages.js';
if (some_condition_based_on_page)
{
$css[] = 'some_page_specific.css';
$js[] = 'some_page_specific.js';
}
...
// in your view where you build the head section
foreach ($css as $item)
{
echo "<link rel='stylesheet' href='{$item}' type='text/css'>";
}
...
// in your view where you build the footer
foreach ($js as $item)
{
echo "<link src='{$item}' type='text/javascript'>";
}
The simplest and more portable way would be to include all files matching a certain pattern, e.g., /components/component1/header.css
This would present two complications. One is performance (you need to check all the directories of all your components). The other is isolation of components, i.e., what happens if you need a given CSS to be included before or after another which might or might not be there?
You might try to solve both problems by including a "manifest" in each component, which could specify, at first, the location of any files and where they should be included. Then your processing is reduced to examining the "components" directory and decoding all manifests, and "compiling" this in a series of directive vectors (e.g. $CSSToBeIncludedInThisOrder[] ). You might also serialize the compiled object to a cached file. Of course, any alterations to components should include removal of the compiled meta-manifest.
Later on, you might include in the manifest instruction such as conditional priorities.
All this should be done BEFORE anything is sent to the client's browser (what if component ZZZ wishes to alter the ob_ state, or maybe the encoding, or is a download override component and wants to send a Content-Type of application/octet-stream?), but the "compilation" should allow to keep perceptual latency low.
So let me clarify:
1. index.php checks whether a metamanifest.cache file exists.
2. If it does, it runs something like
$__META = unserialize(file_get_contents($METACACHE));
and goes on to #4.
3. If it does not, opendirs/readdirs the components directory,
looks what files are there, decides (but does not do yet) what to do with them,
placing those decisions in $__META, e.g. $__META['HeaderJS'][].
4. Now HTML generation begins: the __META array is walked and everything that
needs doing gets done (headers, inclusion of JS in heads, etc.).
Phase #3 might even perform some duplicate checks or versioning, say you have two components that both need "jQuery.js" to be included; instead of blindly appending "/components/comp1/js/jQuery.js" and "/components/comp2/js/jQuery.js" to a __Meta['HeaderJS'], the system could declare a conflict or decide it is solved by including only one of them, thereby further reducing processing time.
I use Taglist in VIM, but one particular PHP application which I have inherited is coded with if()'s and elseif()'s and include()'s extensively. Not a single method or function in almost 5000 lines of code per file (and tens or hundreds of files). Is there any way to use Taglist or another plugin to get an overview of the code flow? I'm thinking of something along the lines of showing the conditions in the if()'s in a concise manner in the sidebar, including their hierarchy. Anything remotely close to that would be great.
Thanks!
this involves a little bit work, you'll need to compile a modified version of exuberant ctags with modified rules for php.
you might want to have a look over here:
http://ctags.sourceforge.net/EXTENDING.html
Using foldlist plugin along with foldmethod-syntax (or tweaking your own foldmethod-expr) would work nicely.
In fact, even without the plugin I believe a proper fold setting would work miracles.
Some recommendations:
set foldmethod=syntax or (set foldmethod=expr and set foldexpr=... for your case)
set foldclose=all to hide all those nasty ifs
set foldcolumn=2 or greater to see the nesting level
set foldtext=MyFoldText() and make a function to show you relevant information,
like:
function! MyFoldText()
let line = getline(v:foldstart)
let line = substitute(line, 'if(\(.*\)).*', 'if: \1', 'g')
" ... etc
return line
endfunction
I'd like to use this function:
ob_start('no_returns');
function no_returns($a) {
return str_replace(
array("\r\n","\r","\n","\t",'','',''),
'', $a);
}
But when I do, it completely kills Disqus comments so I'd like to ignore the DIV "disqus_thread". How would I go about doing that without using some heavy search?
If you are looking to speed up the download of the web page, you might try another method:
<?php
ob_start('ob_gzhandler');
// html code here
This will compress the output in a much more efficient manner and your browser will automatically decompress the output in real-time before the visitor sees it.
A related thread on-line is here: http://bytes.com/topic/php/answers/621308-compress-html-output-php
(This is the PHP way to compress web pages without using the webserver configuration. For example apache+gzip/mod_deflate on apache as mentioned above)
Try Regular Expression and preg_replace
I am building a English/french website and was wondering if there is a best practice for such a job.
Duplicating the site and making a french and english folder with the appropriate site inside.
Using PHP to swap the content with html tags.
eg. if($lang=='en'):
Use php to swap only the content leaving the html tags the same for both. eg. if statements all over the place. Would this be bad for efficiency?
Any other suggestions would be appreciated
We have a framework in place for when (if) our site goes international that works like this...
Folder structure;
/
lang/
english/
images/
text/
dutch/
images/
text/
Any text or images that are language specific are removed from the page directly and replaced by constants. eg On the login screen, we drop in;
echo TEXT_LOGIN_WELCOME;
which is defined in /lang/english/text/login.php as;
define('TEXT_LOGIN_WELCOME', 'Welcome, please login:');
but in /lang/dutch/text/login.php it's defined as;
define('TEXT_LOGIN_WELCOME', 'Welcome, please login (in dutch):');
;-)
Each language define file is named exactly the same as the page it is used for, so when we load a public-facing page, we only need to figure out which language the user speaks and we can include the relevant language define file.
The good thing about this system is that all the language info is centralised. When you need to add a new language, simply copy the main (english?) folder, rename it, zip the whole thing up and send it to a translation service to work their magic. Of course, the downside of this system is the maintenance as both languages and content grow... If anyone has any bright ideas with regard to this then I'd love to hear them!
Btw, if you end up needing to guess a user's location by IP, you might want to check out geoIP.
Use a templating system. Smarty Template Engine is probably one of the most well-known PHP ones. Not only does a templating system serve the exact purpose you're trying to accomplish, it also makes maintaining pages far easier by separating the display code from the content (which also allows you to use the same template for lots of different content pages of a similar nature).
As the simplest way I recommend you to use i18n internationalization method & gettext catalogs (.po files).
The famous WordPress project is using it as well.
1 - Duplicating the entire site will force you to repeat every code touch-up into the 2 folders :-[
2 - If you mean somenting like
<?php if($lang=='en') { ?>
<p>English text</p>
<? } else { ?>
<p>Text français</p>
<? } ?>
This solution is perfect to manage two languages in the same page.
But you still have duplicated tags.
3 - Change only content it's really satisfaction.
Maybe proliferate of if statements can weigh down php compiling... I don't know.
Anyway document can be more concise with this approach:
<?php
function interpreter($buffer) {
$pieces = explode('#', $buffer);
if (isset($_GET['lang'])) $begin=$_GET['lang'];
else $begin = 1; // 1 to display français, 2 to display english
$tot = count($pieces);
for ($i=$begin; $i<$tot; $i+=3) { // remove one language
unset($pieces[$i]); }
foreach ($pieces as $value) { // recompose the text
$output .= $value; }
return $output;
}
ob_start("interpreter");
?>
#Français#English#
<p>#English text#Texte français#.</p>
<?php ob_end_flush() ?>
The text between ob_start and ob_end_flush is parsed AFTER php compiling.
That means are affected strings coming eg. from echo statement, not inside < ?php ?> tags.
Also content coming from php include IS affected.
But NOT external css or javascript.
Keep attention delimiter # isn't a caracter yet used elsewhere.
Maybe you'll prefer to replace with || or ^^
Of course in the future you can adapt this solution into 3 languages or more. But if you have to insert the "Third language translation#" in many lines of a big site, maybe the solution from MatW fits you.