I would like to hide the unused js and css files from the php page.
Some of the js files are unused by some pages, so I would like to hide them. By hidding them I can make webpage faster and get good grade in pagetest.
I used simple php code to hide the code for one page. Works good, the file is hidden for that page, for other pages the code not works. It is displaying text instead of link , like a text in textarea..
<?php
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$currentp=curPageName();
if($currentp=="main1.php"){
echo "";
} else {
//works
echo "<link type=\"text/css\" rel=\"stylesheet\" href=\"../rws.css\" />";
/// not works
echo "<link type=\"text/css\" rel=\"stylesheet\" href=\"http://img.y.com/rws.css\" />";
}
?>
The code works for /rws.css, if I use a http://url.com/rws.css it wont.
Here an example :
<?php
function get_current_file_name () {
$Exploded_Data = explode(‘/’, $_SERVER['PHP_SELF']); //explode the path to current file to array
$Exploded_Data = array_reverse ($Exploded_Data); //reverse the arrays order cos php file name is always after last /
$CurrentPage = $Exploded_Data[0]; // assign the php file name to the currentpage variable
return $CurrentPage;
}
$CurrentPage = get_current_file_name ();
if($CurrentPage!="main1.php"){
echo('<link type="text/css" rel="stylesheet" href="style1.css" />');
}
else if$CurrentPage!="main2.php"){
echo('<link type="text/css" rel="stylesheet" href="style2.css" />');
}
?>
You can use __FILE__ instead of $_SERVER['PHP_SELF']
Is the code getting the correct current page and it's entering the ELSE?
you can use singles quotes and inside double quotes to make sure you're not missing any escape.
if($currentp!="main1.php"){
echo('<link type="text/css" rel="stylesheet" href="http://img.y.com/rws.css" />');
}
Related
I am having trouble preloading CSS on my WordPress site. I was writing a script to find every JS and CSS script enqueued in the footer, and preload it in the <head>. The code for the JS scripts works fine (when I go to page source on the site, I can see the <link> tags with the preload attribute inside), but the CSS preload link tags aren't showing up.
It is very likely I am doing this completely wrong, as I found working code for the JS scripts and then tried to alter it to get it to work for the CSS. For instance, I don't think the version appendage applies to CSS, but I assumed it would still work since it would default to false, right?
As a related question, I am having the same issue with webfonts. Google Pageview Insights is telling me to preload webfonts, so I added some php to do that, but when I run pageview insights again, no dice.
Here is the code:
add_action('wp_head', function () {
global $wp_scripts;
global $wp_styles;
foreach($wp_scripts->queue as $handle) {
$script = $wp_scripts->registered[$handle];
//-- Check if script is being enqueued in the footer.
if($script->extra['group'] === 1) {
//-- If version is set, append to end of source.
$source = $script->src . ($script->ver ? "?ver={$script->ver}" : "");
//-- Spit out the tag.
echo "<link rel='preload' href='{$source}' as='script'/>\n";
}
}
foreach($wp_styles->queue as $handle) {
$style = $wp_styles->registered[$handle];
if ($style->extra['group'] === 1) {
$source = $style->src . ($style->ver ? "?ver={$style->ver}" : "");
echo "<link rel='preload' href='{$source}' as='style' onload='this.rel = \"stylesheet\"'/>\n
<noscript><link rel='stylesheet' href='{$source}'/></noscript>\n";
}
}
//This is the code to preload webfonts
echo "<link rel='preload' href='/wp-content/themes/salient/css/fonts/fontawesome-webfont.woff?v=4.2' as='font' type='font/woff'>";
echo "<link rel='preload' href='/wp-content/themes/salient/css/fonts/fontawesome-webfont.ttf?v=4.2' as='font' type='font/ttf'>";
}, 1);
Welcome to StackOverflow!
A function that I have used in my projects for preloading CSS effectively is:
function add_rel_preload($html, $handle, $href, $media) {
if (is_admin())
return $html;
$html = <<<EOT
<link rel='preload' as='style' onload="this.onload=null;this.rel='stylesheet'"
id='$handle' href='$href' type='text/css' media='all' />
EOT;
return $html;
}
add_filter( 'style_loader_tag', 'add_rel_preload', 10, 4 );
A similar function could in theory be used for JS and Webfonts, but this has only been tested with CSS.
Hope this is helpful!
The exact code, which has worked for me:
function preload_for_css ( $html, $handle, $href, $media ) {
if ( is_admin () )
{
return $html;
}
echo '<link rel="stylesheet preload" as="style" href="' . $href . '" media="all">';
}
add_filter ( 'style_loader_tag', 'preload_for_css', 10, 4 );
It will pass GTmetrix and Google Insights test. At least passed for me :-)
I would like to import a css stylesheet in a page depending on a php condition (or other), this condition is based upon the domain URL.
For example, if the page loaded is "mydomain.com/about-us" import a "css/about-us.css" file.
I have tried with this code, but it does not work.
<?php
$url = $_SERVER['REQUEST_URI'];
if (strstr($url, "mydomain.com/about-us/")) {
include '/css/about-us.css';
}
?>
How can I import, or use a <style> tag conditionally?
solution correct:
the correct solution is use only the page name, so if you page is mydomain.com/about-us/
use " /about-us/" only.
now have other question, with the code posted you can import css for specific page , but I noticed that if the domain is mydomain.com/about-us/team.html example in the page team.html load also the css of "about-us" how load the css for about-us only in the page mydomain/about-us/ ??
How you can read here, strstr will return a string or FALSE. You can change it like this:
<!DOCTYPE html>
<head>
<?php
if (strstr($_SERVER['REQUEST_URI'], "mydomain.com/about-us/")!=false) {
echo '<link rel="stylesheet" type="text/css" href="/css/about-us.css">';
} ?>
</head>
...
</body>
</html>
Or:
<!DOCTYPE html>
<head>
<style type="text/css">
<?php
if (strstr($_SERVER['REQUEST_URI'], "mydomain.com/about-us/")!=false) {
echo file_get_contents('/css/about-us.css');
} ?>
</style>
</head>
...
</body>
</html>
In the first example your CSS is included through the <link> tag, in the second, the PHP-script loads your CSS file into the script-tags. You can not use include because it will load another php file and execute where it was included. You should use my first example, because it is more server-friendly because the CSS file doesn't need to be read. Your page will be faster.
You can add a stylesheet to the page with PHP by including this in the <head> of your html document:
<?php
echo '<link rel="stylesheet" type="text/css" href="' . $file . '">';
?>
Where $file is the name of the css file. You're going to have to provide some more information as to what you're trying to do for a better answer.
Update
The variable $_SERVER[REQUEST_URI] only gives the requested page, not the whole domain. From the PHP manual,
'REQUEST_URI'
The URI which was given in order to access this page; for instance, '/index.html'.
So the code should look as follows:
<?php
$requested_page = $_SERVER['REQUEST_URI'];
if ($requested_page === "/about-us" || $requested_page === "/about-us/") {
echo '<link rel="stylesheet" type="text/css" href="/css/about-us.css">';
}
?>
This will test if the requested page is "/about-us" (the client is requesting the "about-us" page) and if it does, the link to the stylesheet will be echoed.
use this:
<?php
$url = $_SERVER['REQUEST_URI'];
if (strstr($url, "mydomain.com/about-us/"))
{
// output an HTML css link in the page
echo '<link rel="stylesheet" type="text/css" href="/css/about-us.css" />';
}
else
{
// output an HTML css link in the page
echo '<link rel="stylesheet" type="text/css" href="/css/another.css" />';
}
?>
you can also do this to import the css contents directly, but probably some media/images links can break:
<?php
$url = $_SERVER['REQUEST_URI'];
if (strstr($url, "mydomain.com/about-us/"))
{
// output css directly in the page
echo '<style type="text/css">' .file_get_contents('./css/about-us.css').'</style>';
}
else
{
// output css directly in the page
echo '<style type="text/css">' .file_get_contents('./css/another.css').'</style>';
}
?>
Is it possible to call a different css file depending on which dynamic page you're on?
For example if you start at index.php ->
You then click a link that refers to index.php?p=apple
If you have a css file called index.css that is specific to index.php, can you have a css file that overides index.css in the event that index.php?p=apple is opened?
If there is no solution, i may just rewrite my css file to accommodate all the dynamic pages.
UPDATE: The following is some extract of my code.
Note: in the something.inc.php page is a link to index.php?p=apple
<head>
<link href="css/index.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<?php
$pages_dir = 'pages';
if (!empty($_GET['p'])) {
$pages = scandir($pages_dir, 0);
unset($pages[0], $pages[1]);
$p = $_GET['p'];
if (in_array($p.'.inc.php', $pages)) {
include ($pages_dir.'/'.$p.'.inc.php');
} else {
echo 'Sorry, page not found';
}
} else {
include($pages_dir.'/something.inc.php');
}
?>
UPDATE 2: Used the solution marked as answer, and it's all working well. Thanks everyone for the help!
$link = (isset($_GET['p']))? $_GET['p'] : 'index';
if(file_exists(PATH_TO_CSS_FILES.$link."css")){
echo "<link src='$link.css' media='all' rel='stylesheet' type='text/css'>";
} else {
echo "<link src='index.css' media='all' rel='stylesheet' type='text/css'>";
}
If your url are index.php?p=apple or index.php?p=orange
Then
if($_GET['p'] == 'apple')
{
echo '<link href="css/apple.css" type="text/css" rel="stylesheet">';
}
elseif($_GET['p'] == 'orange')
{
echo '<link href="css/orange.css" type="text/css" rel="stylesheet">';
}
If your url are index.php or product.php
Then
$file = basename($_SERVER['REQUEST_URI']);
if($file == 'index.php')
{
echo '<link href="css/apple.css" type="text/css" rel="stylesheet">';
}
elseif($file == 'product.php')
{
echo '<link href="css/orange.css" type="text/css" rel="stylesheet">';
}
One way i think is that you can generate the CSS link dynamically based on the querystring . You can have separate php file which will act as helper file and you can include in all the pages.
if($_GET['p'] == 'a')
{
echo LINK OF NEW CSS File
}
else
{
echo Link of another CSS
}
maybe...
$page = (isset($_GET['p'])) ? $_GET['p'] : false;
if ($page){
$css = '';
switch ($page) {
case 'apple':
$css = 'apple.css';
break;
//other options here
}
//link to $css
}
And remember to use !important in all styles aimed to override original.
What is the way to concatenate multiple css files into one line with php?
I want to reduce the following ..
<link href="reset.css" rel="stylesheet" type="text/css" media="screen">
<link href="grid.css" rel="stylesheet" type="text/css" media="screen">
<link href="commons.css" rel="stylesheet" type="text/css" media="screen">
into
<link href="concatenator.php+reset.css+grid.css+commons.css" rel="stylesheet" type="text/css" media="screen">
the result one css or html file with all stylesheet inside
This method reduce the http requests, and have other features for designer and developer with use dinamyc sites configurations.
The code posted by MatRt is close, but is using + signs instead of . signs for the appending and it doesn't seem to actually send the CSS to the page, even though it will print the CSS.
I managed to get the code supplied here working with a small tweak to it. Here it is:
<?php
// Check the parameter and stop if there is no files param
if (empty($_GET['files']))
die();
// Retrieve the list of files
$files = explode(",", $_GET['files']);
$directoryOfCss = 'C:\xampplite\htdocs\path\to\my\folder\css\\';
$cssContent = "";
// Loop on all potential file and try to retrieve its content
foreach($files as $oneFile)
{
//echo $directoryOfCss . $oneFile . ".css";
if (file_exists($directoryOfCss . $oneFile . ".css")){
//echo $directoryOfCss . $oneFile . ".css<br>";
$cssContent .= file_get_contents($directoryOfCss . $oneFile . ".css");
}
}
// Finally echo the total content of CSS
header("Content-Type: text/css");
header("X-Content-Type-Options: nosniff");
header("Content-Type: text/css;X-Content-Type-Options: nosniff;");
echo $cssContent;
I got the headers part from this post.
Your URL should be more like
concatenator.php?files=reset,grid,commons
Note: you can chose other separator if you don't like the ,
And the famous concatenator.php could be like
<?php
// Check the parameter and stop if there is no files param
if (empty($_GET['files']))
die();
// Retrieve the list of files
$files = explode(",", $_GET['files']);
$directoryOfCss = "/absolute/path/to/your/css/files/";
$cssContent = "";
// Loop on all potential file and try to retrieve its content
foreach($files as $oneFile)
{
if (file_exists($directoryOfCss + $oneFile + ".css"))
$cssContent += file_get_contents($directoryOfCss + $oneFile + ".css");
}
// Finally echo the total content of CSS
echo $cssContent;
I am developing a site using PHP, XHTML strict, and jQuery that will be flexible to support both mobile and desktop devices, using the Responsive Web Design approach and serving different stylesheets using the min-device-width property.
<link rel="stylesheet" href="css/960.css" type="text/css" media="screen and (min-device-width: 480px)" />
But the site will need to have a link to toggle the "desktop" and "moblie" view. I have a basic idea of how this could be done using jQuery, but would prefer a solution in php for devices that don't support JavaScript.
PHP isn't too hard to implement this with. If you were to use a link, like so...
Desktop view
Then in your page script...
//test for stylesheet parameter
if(isset($_GET['view']))
{
//save and set it in the session
$stylesheet = $_GET['view'];
$_SESSION['stylesheet'] = $stylesheet;
}
elseif(isset($_SESSION['stylesheet']))
{
//parameter not sent, so get it from the session
$stylesheet = $_SESSION['stylesheet'];
}
Later, you select your stylesheet code based on this $stylesheet variable.
if($stylesheet == 'desktop')
{
echo '<link rel="stylesheet" href="/css/desktop.css" type="text/css" />';
}
elseif($stylesheet == 'mobile')
{
echo '<link rel="stylesheet" href="/css/mobile.css" type="text/css" />';
}
else
{
echo'<link rel="stylesheet" href="css/960.css" type="text/css" media="screen and (min-device-width: 480px)" />';
}
You could use a SESSION variable for that. The following example assumes there are two stylesheets mobile.css and desktop.css
Testing the argument, and setting up the session.
<?php
session_start();
if(isset($_GET['style']))//Tests the argument
{
if($_GET['style']=="desktop")//This to prevent passing wrong arguments
{
$_SESSION['style']=$_GET['style'];
}
if($_GET['style']=="mobile")//This to prevent passing wrong arguments
{
$_SESSION['style']=$_GET['style'];
}
}
?>
<head>
blah
<?php
if(isset($_SESSION['style'])
{
echo '<link rel="stylesheet" href="'.$_SESSION['style'].'.css" type="text/css" media="all" />';
}
?>
</head>
Your link to switch from/to desktop CSS.
Desktop version
Mobile version
Well, why not just include the appropriate stylesheet depending on a query parameter, or session variable or UA etc etc
//Code that figures out what type is
$css = '';
switch ($type) {
case 'mobile':
$css = '<link rel="stylesheet" href="css/960.css" type="text/css" />';
break;
case 'touch':
$css = '<link rel="stylesheet" href="css/960-mobile.css" type="text/css" />';
break;
case 'desktop':
default:
$css = '<link rel="stylesheet" href="css/960-full.css" type="text/css" />';
break;
}
In your view
echo $css;
NOTE This is only an example. Ideally you shouldn't be constructing your whole link html in PHP, but not knowing any of your implementation details, it will suffice. Best way to do it would be to name your CSS files in a standard manner with only a -type at the end to differentiate where each file is used and just pass the $type variable to the view.
Is this what you're looking for?