js and css on-demand loading - php

i am confused by the concept of on-demand loading
I saw this blog post and was wondering if I could do the same with php using the ff. approach:
check current url
serve css or js based on current url
which may be done like this in Kohana
if (uri::segment(1) == 'search') // check current url
echo html::stylesheet('search.css'); // serve stylesheet
echo html::script('search.js'); // serve script
endif;
or am I getting the idea wrong?
a side question would be is ti alright to have a css file for each individual page aside from the site-wide forms.css and layout.css

you can use your approach. css files are better served in the head and so you can put your conditions in the site wide template.
for javascript, which should be served at the bottom of your html, you can simply put your tags directly in your application/view/your_action.php without using any url based condition.
about
would be is ti alright to have a css
file for each individual page aside
from the site-wide forms.css and
layout.css
well, you can do it but keep in mind that this will generate an extra request (for the css files) for every new page visited by the user. if performance is critical you'd better serve a unique compressed css.

Here is an example for HTML and PHP using REQUEST_URI. the variable will hold the page you're at, you might want to do some parsing of it to get the exact page with out slashes etc, it's usually a relative path to the document from the root.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>
<?php
switch($_SERVER['REQUEST_URI']) {
case "/home.php":
echo '<link type="text/css" href="home.css" rel="stylesheet" />';
echo '<script type="text/javascript" src="js/home.js"></script>';
break;
case "/about.php":
echo '<link type="text/css" href="about.css" rel="stylesheet" />';
echo '<script type="text/javascript" src="js/about.js"></script>';
break;
case "/contact.php":
echo '<link type="text/css" href="contact.css" rel="stylesheet" />';
echo '<script type="text/javascript" src="js/contact.js"></script>';
break;
default :
echo '<link type="text/css" href="default.css" rel="stylesheet" />';
echo '<script type="text/javascript" src="js/default.js"></script>';
break;
}
?>
</head>
<body>
My Page
</body>
</html>

Related

How can I call a specific CSS file based on a specific HTML class on the page?

For example, my site has 5 CSS files like this...
<link rel="stylesheet" href="/templates/purity_iii/css/custom_marketing.css" type="text/css" />
<link rel="stylesheet" href="/templates/purity_iii/css/custom_gps.css" type="text/css" />
<link rel="stylesheet" href="/templates/purity_iii/css/custom_fleet.css" type="text/css" />
<link rel="stylesheet" href="/templates/purity_iii/css/custom_service.css" type="text/css" />
<link rel="stylesheet" href="/templates/purity_iii/css/custom_corporate.css" type="text/css" />
Every page of the site will be in one of those "categories" (i.e. marketing, gps, fleet, service or corporate). And this is indicated by a class on the HTML tag. So something like this at the top of every page...
<html class="gps">
I currently have EVERY page calling all 5 style sheets listed above, but it only NEEDS the corresponding style sheet, so I'd like to be efficient if possible.
Is there a way using PHP (or whatever makes sense) to essentially search the tag's class for "gps" or "fleet" (etc.) and if, for example, it found "gps", I could then echo only that style sheet, i.e...
echo "<link rel="stylesheet" href="/templates/purity_iii/css/custom_gps.css" type="text/css" />";
This totally depends on how PHP generates your HTML. Another possibility is to do this with JavaScript. You can do it like this:
<script type="text/javascript">
var file = 'templates/purity_iii/css/custom_' + document.documentElement.className + '.css';
var link = document.createElement('link');
link.href = file;
link.type = 'text/css';
link.rel = 'stylesheet';
document.getElementsByTagName('head')[0].appendChild(link);
</script>
You can for example place the code above between <head> and </head>. Not really a valid answer to your question (PHP solution), but you could consider this as an alternative.
This seems like a poor strategy, albeit I don't know the size of your CSS files and other parameters.
How different are these pages as far as their style goes? From the file names above it looks like you might have a lot of redundant (duplicate) CSS selectors in each file. How much of the CSS in each of those files is actually unique? Is it 5k? 10k? 50k? If it's fairly small, go ahead an put it all in one file. By placing it in one file all the CSS for all the pages of your site will be cached in the user's browser and no additional requests would be needed for subsequent pages.
If combining all files and you have a 500k file and 250k is for a single page then splitting it would make more sense.
A PHP Solution
I'm guessing that your setting the CSS class on the <html> tag with PHP. If so, why not check the value of that variable in your PHP script and add the appropriate CSS file.
Something like this:
<html class="<?php echo $page_class; ?>">
<head>
<link href="custom_<?php echo $page_class; ?>.css">
</head>
This is advice is fairly general but hopefully it points you in the right direction.
try something like
<?php
if($page_type = 'gps')
{
?>
<link rel="stylesheet" href="/templates/purity_iii/css/custom_gps.css" type="text/css" />
<?php
}
elseif($page_type = 'marketing')
{
?>
<link rel="stylesheet" href="/templates/purity_iii/css/custom_marketing.css" type="text/css" />
<?php
}
?>

PHP + JQuery - How to use these two together? Please see my example

I have a php based website. As in, all of the pages html is output via php.
Here is a simple example:
<?php
ob_start();
$pageStart = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MY WEBSITE PAGE</title>
</head>
<body>
<p>CONTENT</p>
</body>
</html>
';
echo $pageStart;
exit;
?>
What i would like to do is make use of some jquery in this page.
So naturally my first attempt was to include the script inside of the php variable like so:
<?php
ob_start();
$pageStart = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var datefield=document.createElement("input")
datefield.setAttribute("type", "date")
if (datefield.type!="date"){ //if browser doesn't support input type="date", load files for jQuery UI Date Picker
document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
}
</script>
<script type="text/javascript">
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($){ //on document.ready
$('#birthday').datepicker();
})
}
</script>
</head>
<body>
<p>CONTENT</p>
</body>
</html>
';
echo $pageStart;
exit;
?>
Now, I use dreamweavers code editor, which due to the syntax highlighting feature, will point out the masses of syntax errors produced in this.
So i at first attempted to slash out these errors. This failed.
So i tried changing the "s to 's, and visa versa, until the errors were gone. This failed too as it seems the script will not validate in this manner.
So i read a few tutorials, and found this one:
JavaScript and PHP may each bring great potential to any Web development effort, but they don't always play nice together. Read about the problems.
And the way I understand it, is that you'd need to include the js rather than have it as part of your php directly.
So have a file called page.php and another called jquery.php. So I decided to try and modify this idea to suite my problem.
So i started with something like this - index.php:
<?php
ob_start();
$pageStart = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MY WEBSITE PAGE</title>
'. include $_SERVER['DOCUMENT_ROOT'] . '/../../path/to/include/datepicker.php'.'
</head>
<body>
<p>CONTENT</p>
</body>
</html>
';
echo $pageStart;
exit;
?>
And - datepicker.php:
<script language="Javascript">
var datefield=document.createElement("input")
datefield.setAttribute("type", "date")
if (datefield.type!="date"){ //if browser doesn't support input type="date", load files for jQuery UI Date Picker
document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
}
</script>
<script language="Javascript">
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($){ //on document.ready
$('#birthday').datepicker();
})
}
</script>
Now there are no syntax errors in either page, great... So I try it, half expecting things to finally just work...
Nope... Fatal Error: failed to open stream: No such file or directory blah blah. This error relates to the include that i added. So okay, even though the file is there, it is not being validated as php because there are no opening and closing php tags.
So I add them... Annnd... A page full of syntax errors again!
So my question is this:
Could some please share some knowledge and explain to me roughly how this process actually works. Whats the deal with all the syntax errors, and how are you supposed to go about a task like this?
I believe it is possible, and yes it would ceratinly be easier if i was not outputting the entire html via php. But this is a simple example and my actual design is alot more complex. It requires for the different parts of the page to be broken up into variables, in order to place those bits and peices when needed, dynamically.
Any input, suggestions, or insight would be greatly appreciated; and any links to pages or tutorials that cover this would also be greatly appreciated.
Thank You!!
All you need to do to use jQuery with PHP is to include the jQuery javascript file in your HTML document in the head tag. I actually use PHP along with jQuery all the time. And this is how I do it. In your code above, it looks like you have some escaping issues with your code. And it also looks like you want to hold the header of the page in a PHP variable then print it out. You don't have to do all that. Just put the plain text in your PHP file without any php tags and it will work. Also, you are using an old version of jQuery. Should probably use the latest version. But, if you need it stored in a PHP variable so that you can print it out, do this:
SO, here is some code to get you started.
<?php
$pageStart = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MY WEBSITE PAGE</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#date").datepicker();
});
</script>
</head>
<body>
<input type="text" id="date" name="date" />
</body>
</html>';
print $pageStart;
?>
<head>
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// javascript & jquery code
// even better would be if you would put client code in separate file!!!
});
</script>
</head>
<body>
<?php
echo "bla bla bla";
?>
</body>
and +1111 to # Heera's comment
You're missing the basics's.
Use Heredoc. Thousands of syntax errors will be gone.
See the heredoc version of your pages,
http://pastie.org/3412925
http://pastie.org/3412929
http://pastie.org/3412935 // Here you have used include to contact. include does not return anything. It just includes. So Its changed differently.
I think it should be
. (include ($_SERVER['DOCUMENT_ROOT'] . '/../../path/to/include/datepicker.php')) .
otherwise php will try to include all the stuff after until the l is reached (tags will be interpreted as part of the file name).
also, in terms of the php code, after the file is included (on success), the include statement translates into 1 as a number, instead of the content of the file.
use
<? $abc <<<qwerty
...
...
...
qwerty;
return qwerty;
?>
for all the files that you want to include

Include a js and css file only in a specific view

In my CodeIgniter application have a common header and footer view, which I include in different views. My header_view is as simple as:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><?php echo $page_title;?></title>
<link rel="stylesheet" href="<?php echo base_url();?>/css/master.css" type="text/css" media="screen" />
<script src="<?php echo base_url();?>js/common.js" type="text/javascript"></script>
</head>
<body>
<!-- end of header -->
Now Lets suppose I have another view called form_view, where I would like to include a CSS file form.css and a javascript file form.js. Since these files are only used in form_view, I don't want to add them in the header_view, because then they will be included in all of the views in my application.
So my question remains, how can I include a specific css or a specific javascript file on a specific view, when using a common header like above.
Thanks.
You could write something like Zend_Bootstrap and run it before views. The bootstrap file will be responsible for setting css and js files so your header will just grab them from an array.
Bootstrap:
$head_array = array(
'css' => array(
'/static/css/style.css',
'/static/css/style1.css'
),
'js' => array(
'/static/js/script.js'
)
)
if($view == 'view_form') {
$head_array['css'][] = '/static/css/form.css';
}
Of course this example is very primitive but it shows the idea.

How to import/include a CSS file using PHP code and not HTML code?

I have googled a lot but it seems that I am doing something wrong.
I want to do this:
<?php
include 'header.php';
include'CSS/main.css';
...
?>
However, my page prints the CSS code.
Note: I want to use PHP to include the CSS file, and not use
I also do you want to rename my CSS file to a PHP file as some website mentioned.
Any clues?
Many thanks.
You have to surround the CSS with a <style> tag:
<?php include 'header.php'; ?>
<style>
<?php include 'CSS/main.css'; ?>
</style>
...
PHP include works fine with .css ending too. In this way you can even use PHP in your CSS file. That can be really helpful to organize e.g. colors as variables.
You are including the CSS code as text in your PHP page. Why not just link it in the traditional fashion?
<link rel="stylesheet" href="CSS/main.css" type="text/css">
you can use:
<?php
$css = file_get_contents('CSS/main.css');
echo $css;
?>
and assuming that css file doesn't have it already, wrap the above in:
<style type="text/css">
...
</style>
To use "include" to include CSS, you have to tell PHP you're using CSS code. Add this to your header of your CSS file and make it main.php (or styles.css, or whatever):
header("Content-type: text/css; charset: UTF-8");
This might help with some user's connections, but it theoretically (read: I haven't tested it) adds processor overhead to your server and according to Steve Souder, because your computer can download multiple files at once, using include could be slower. If you have your CSS split into a dozen files, maybe it would be faster?
Steve's blog post: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/
Source: http://css-tricks.com/css-variables-with-php/
<?php
define('CSSPATH', 'template/css/'); //define css path
$cssItem = 'style.css'; //css item to display
?>
<html>
<head>
<title>Including css</title>
<link rel="stylesheet" href="<?php echo (CSSPATH . "$cssItem"); ?>" type="text/css">
</head>
<body>
...
...
</body>
</html>
YOUR CSS ITEM IS INCLUDED
This is an older post, however as the info is still relevant today an additional option may help others.
Define a constant for the file path per Stefan's answer. The
definition can be placed at the top of the PHP page itself, or within
an included/required external file such as config.php.
(http://php.net/manual/en/function.include.php)
Echo the constant in PHP tags, then add the filename directly after.
That's it!
Works for other linked files such as JavaScript as well.
<?php
define('CSS_PATH', 'template/css/'); //define CSS path
define('JS_PATH', 'template/js/'); //define JavaScript path
?>
<!-- Doctype should be declared, even in PHP file -->
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo CSS_PATH; ?>main.css">
<script type="text/javascript" src="<?php echo JS_PATH; ?>main.js"></script>
</head>
<body>
</body>
</html>
If you want to import a CSS file like that, just give the file itself a .php extension and import it anyway. It will work just fine :)
You can also do the following:
Create a php file in includes folder, name it bootstrap_css.php for example
paste the css code files to file created above
<?php
$minCss=' <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">';
$business = '<link href="bootstrap/css/modern-business.css" rel="stylesheet">';
echo $minCss;
echo $business;
?>
in the html header, include the css files as follows
<?php include_once 'includes/bootstrap_css.php'; ?>
You could do this
<?php include("Includes/styles.inc"); ?>
And then in this include file, have a link to the your css file(s).
I don't know why you would need this but to do this, you could edit your css file:-
<style type="text/css">
body{
...;
...;
}
</style>
You have just added here and saved it as main.php. You can continue with main.css but it is better as .php since it does not remain a css file after you do that edit
Then edit your HTML file like this. NOTE: Make the include statement inside the tag
<html>
<head>
<title>Sample</title>
<?php inculde('css/main.css');>
</head>
<body>
...
...
</body>
</html>
I solved a similar problem by enveloping all css instructions in a php echo and then saving it as a php file (ofcourse starting and ending the file with the php tags), and then included the php file.
This was a necessity as a redirect followed (header ("somefilename.php")) and no html code is allowed before a redirect.
Just put
echo "<link rel='stylesheet' type='text/css' href='CSS/main.css'>";
inside the php code, then your style is incuded. Worked for me, I tried.
This is the format of what I have which works:
<head>
<title>Site Title</title>
<?php include 'header.php'; ?>
</head>
Inside my header.php I have:
<!doctype html>
<html class="no-js" lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/png" href="assets/images/icon/favicon.ico">
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
The file name must be something other than a .CSS index. Write the following:
<link rel="stylesheet" href="style.css" type="text/css" />
The best way to do it is:
Step 1:
Rename your main.css to main.php
Step 2: in your main.php add
<style> ... </style>
Step 3: include it as usual
<?php include 'main.php'; ?>
That is how i did it, and it works smoothly..
_trace its directory, I guess
echo css('lib/datatables_rqs/jquery.dataTables.css');

Using includes and stylesheets for a specific page?

I was about to use includes for my websites, setting up includes for
the header, footer, nav, etc. In the header I added the DOCTYPE to the end of the </head> tag.
If I do it this way, how would I add a stylesheet just for one specific page if the head of the page is in a include?
well there are alot of various ways to do this one would in the included header php file
add an variable
like so
<?=#$css;?>
and then in the file that includes it define the css variable to whatever you want to be included
$css = 'something';
include(header.php);
if this is your header.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<?=#$css;?>
</head>
and this is your index.php
$css= '<link href="style.css" rel="stylesheet" type="text/css" />';
include('header.php');
You could use php on the header page to detect what page the user is on, and display the relevant stylesheet.
<?php
$page = $_SERVER["REQUEST_URI"];
$clean = array("/", ".php");
$page = str_replace($clean, "", $page);
echo "
<link href=css/$page.css media=screen rel=stylesheet type=text/css />";
?>
If you are on index.php, then this script will include index.css, main.php will include main.css, etc.

Categories