Is this possible? For example, I'm loading all of my css files through my header. One of the things I'm using is the JQuery DataTables plug-in. However, I don't want to load the DataTables css unless the page content contains a DOM element of type "table". I've tried evaluating the page with:
file_get_contents($_SERVER["PHP_SELF"];
Which doesn't work. What's the most efficient way to evaluate开发者_C百科 your page's content in PHP, and load CSS files appropriately? Or, is javascript a better way to do this?
I would say you're over thinking this. Set a far away cache expiration date on your DataTable css and simply let the user cache the css file.
This could be done using output buffering, but it sounds like a bad idea to collect the whole document, analyze it, and then add a style sheet header - it's likely to be slow, kludgy and may even hit memory limits in the case of huge tables.
I would tend to say always load the CSS files, and see to it that they're properly cached.
I found it easiest to just set some flags in my parent .php file and have the header file check for those flags and modify output as it gets loaded.
index.php:
<?php
$INCLUDE_TABLE_CSS = true;
include('header.php');
header.php:
blah blah blah
<?php if (isset($INCLUDE_TABLE_CSS) && $INCLUDE_TABLE_CSS) { ?>
<link rel="stylesheet" .... href="table.css" />
<? } ?>
blah blah blah
Unless you've got a large number of conditional settings, then this is fairly simple to manage.
Javascript is a better way to do this. You can do a deferred inclusion, sometimes called "lazy load". Within domready
, you would check for the presence of a given class, let's say dataTable
. If there are any elements with this class, you inject a new <script>
or <link>
tag into the header with a reference to the javascript or css file containing the needed script/styles. The <script>/<link>
tag's onload event will be the callback to trigger whatever initialization you have to do once the script is in place.
My apologies that I can't tell you the jQuery way (I am a Mootools guy), but in Mootools there is a class called Asset
that manages the creation of the <script>/<link>
tag and the resulting onComplete
event. I'm certain there is a jQuery analog to this.
Use jQuery! This code looks to see if there is a <table>...</table>
object, and if there is, it creates a new <link>
element with your desired CSS file and adds it to the header object.
if ($('table').length>0){
var link = $("<link>");
link.attr({type: 'text/css', rel: 'stylesheet', href: 'tableStyleSheet.css'});
$("head").append( link );
}
精彩评论