If you have a lot of files, would there be any benefit to doing something like this in the header:
<style type="text/css">
<?php
include("css/myCss1.css");
include("css/myCss2.css");
include("css/myCss3.css");
include("css/myCss4.css");
include("css/myCss5.css");
?>
</style>
That way server returns one file instead of several. You can also load the content from js in between script tags.
Please don't flame, just explain why this would or would not make sense in a situation where you need to have a lot of individual files and you want to consolidate instead of having the main file make calls for those files individually.
I've tried and they seem to work... but what are the repercussions on the server or benefits of speed (if any).
Just curious... Thank you very much.
UPDATE: Thank you for all replies... Would another solution (that would deal with the cache issue) be to have 1 external php file that load all the other css into it - sort of combining all into 1?? Does that make sense?
You should use an external stylesheet, so it can be cached separately because in most cases PHP is used for dynamic data retrieved from databases and you might not want to cache all the data. If you are not using PHP for anything else than merging CSS, you should definitely use LESS # http://www.lesscss.org, as it is a CSS preprocessing language that has many features that make developing CSS easier which includes merging css files together. You could also try SASS # http://sass-lang.com/ which is similar. This way you reduce the number of HTTP requests, the server doesn't have to keep running PHP code unnecessarily, and don't do as many reads from disk.
Of course that would work, but since the size of HTML output content remains the same and same number of KiloBytes are sent to the client, there is no real benefit here.
And there could be many downsides, first up it would be hard to debug which file to update when you have to update any css class. You'll have to find that manually.
But one major point against this would be that PHP includes are not meant for CSS includes. Although that might appear to work for you, a source code include is for source code. Its bad programming practice and also it requires PHP to parse all those CSS files unnecessarily. This unwarranted parsing of your CSS files will counter the benefits you will obtain by that. Rather you can simply merge all those CSS files together into one.
In addition to Hanky Panky's answer, when including CSS files with HTML code, browsers may cache the CSS file locally, making less data be transferred between the server and the client.
When including the CSS with PHP like in your question, there can be no such local caching of the CSS.
Edit: Using one single PHP for all the CSS could in theory only work if you include the PHP-CSS as a stylesheet using HTML-code. Writing <style type="text/css"> in either the PHP-CSS file or using include inside such statement in your main file would not help. However, either way it is not something that I would recommend. PHP is not for including many CSS-files into one.
Related
I have a css class:
.footer-react-btn{
color:#ddd;
}
But if I change .footer-react-btn to .a or .b, then I might save some bytes of text from being loaded.
I want it to happen in my production. I will be writing the code in an understandable manner during my development.
So, Is there any way I can do it in?
I am new here. I need an explanation step by step.
Typically, one simply maintains two files -- a-stylesheet.css and a-stylesheet.min.css. And it's usually limited to removing whitespace, not changing names. Imagine if you were using two different stylesheets and applied this same name-changing mechanism to both... You could suddenly have collisions that otherwise wouldn't exist. Plainly, just not a good idea.
At any rate, the closest thing to what you're looking for is django-compressor which combines and minifies your static JS/CSS, but it has many behaviors you may or may not want.
Frankly, it's my opinion that worrying about those few bytes is a waste of time. Simply minifying the CSS is a simpler and safer way to reduce the size of your CSS components. I wouldn't even consider more complex solutions until you really encounter scaling problems.
If you wants to see the fully expanded code in text editor and wants to send the minified css code to clients, use PHP comments.
First of all, make a file with extension php. Eg:- styles.php then add below code into it:
<?php header("Content-type: text/css"); ?>
Then add the minified code. For removing the read-hardness issue, you could add PHP comments like
You just add as many short codes as you wish but don't forget to enter the expanded information inside a PHP comment. The reason I suggested PHP comment instead css comments, is that PHP codes won't be executed by the web server. You can read both minified code and the expanded code(in comments) in the text editor but client browsers will only get the minified code loaded. So, you can decrease that data transferred....
I think that this will be helpful....
The title is maybe a bit misleading. I need to work with huge files (The smallest one is 210 KB), so it isn't a very fast way to get them trough AJAX. I tried including them in a plain text script tag, and it worked, but these files are a couple of thousands lines, so they made the HTML code very very long. The IDE froze, when i tried to delete 3 at once. My question is basically:
Is there a way, to read a code in a separate file, where I could just do
<script src="myFile.ext" id="myFile"></script>
and it would work the same as having it in the main html tag?
You will not be able to use the data in the file included with a script tag, unless it is javascript, and actually calls a function defined on your page.
Read about jsonp.
Your best bet is to use AJAX.
I think the only overhead to load with AJAX is the extra HTTP request headers, and that's negligible comparing to your huge file size. I don't understand why you think it's faster to load together with other HTML.
I am building a front-end UI framework for developers in my firm to use to build internal web apps. It consists of customized Bootstrap, jQuery, other open-source libraries, internal modules and stylesheets. The user environment is entirely IE9 and my server is .NET 3.5. I am hosting the shared files. Dev teams in the firm will place the links in their project pages and apply the framework to their pages.
I want to offer them the simplest method of implementing this which would be one line of code to paste that builds the library for them. Cutting and pasting 30 lines of code is stale the moment Ctrl + V is pressed, it leaves me no control and is simply inelegant.
Failed Experiments
I tried using Head.js and LazyLoad both of which use best practices for inserting scripts. But each of them has caused either content to display before styled or conditions where methods are called before scripts load. I am giving up on this approach.
It's too volatile.
A simple document.write() solution
Over the weekend, I thought: Why don't I just make a js file named "framework,js", add the script and link files in order with a stack of document.write() lines. Tell developers to put it in the head and that's it. Heck I could add the necessary metatags for IE9 and mobile too for that matter. It's so nasty and simple... but it just might work!
The user base is on an internal network and of limited size. Bandwidth is not a problem. I'll test performance before I choose this. I can direct the developer teams on where to place the link.
Knowing this and providing it actually works, is there any reason why I shouldn't do this?
My only other option to explore is bundling on the server. I am hoping not to have to resort to this since I don't own the server myself and I am not a .NET developer.
Your proposed approach is an excellent one for your situation. It has several advantages over the more sophisticated solutions, including utter simplicity, completely predictable order of execution, and full compatibility with scripts that may not lend themselves to asynchronous loading. I have used it many times in production applications, as have many other developers.
Of course the other solutions have their advantages too, but for what you're doing there is nothing wrong with good old document.write().
It sounds like you have a number of scripts and stylesheets and are probably loading them from a common directory (or a common root directory). To reduce repetition in your framework.js file, you might want to define two functions, one to write a <link> tag for CSS and another to write a <script> tag for JavaScript. So a skeleton framework.js file might look something like this:
(function() {
var scriptBase = 'js/';
var styleBase = 'css/';
function writeStyle( name ) {
document.write(
'<link rel="stylesheet" href="', styleBase, name, '">',
'</link>'
);
}
function writeScript( name ) {
document.write(
'<script src="', scriptBase, name, '">',
'</script>'
);
}
writeStyle( 'one.css' );
writeStyle( 'two.css' );
writeScript( 'one.js' );
writeScript( 'two.js' );
})();
Note that you don't have to do any special escaping of the </script> text as you may see in code that uses document.write(). That's only necessary when you're putting this code directly inside a <script> tag within the HTML file. The purpose of that escaping is to prevent the enclosing <script> tag from being closed by the </script> text inside the document.write() call. Since your code is in an external .js file this is not an issue: the presence of the </script> text inside this file won't terminate the .js file.
Another point to keep in mind is that all of the document.write() calls you make inside a .js file are inserted into the document after the .js file that writes them. So don't expect to be able to do a document.write() inside framework.js and then have other code inside framework.js that depends on the .js file you just wrote. All of those .js files (and .css) are loaded after framework.js, not interleaved with it.
One more consideration, of course, is load time. Your page could load faster if you combine and minify your CSS and JS files. But if these are internal web apps, page load time may be the least of your worries: reliability and maintainability may be more important. And in any case you can always use the document.write() solution to get up and running right now, and later optimize this only in the unlikely event that you need to.
I have a blue-ish colour that I want to use in many places in my app and at the moment I am copying and pasting it between styles in my CSS. Is there a way of defining a constant like the standard colours, 'blue', 'red' etc. that I could share between my CSS, my HTML and my JS?
I'd like to be able to say (somewhere, preferably CSS)
myblue = #33CC99
in CSS say...
background-color:myblue;
in HTML say...
<td color="myblue"/>
and in JavaScript
tag.style.backgroundColor = myblue;
I'm guessing this is impossible and google turned nothing up, so has anyone got any ideas? I doubt I am the only person to come across this.
A very promising product that "compiles" higher-level expressions like variables into CSS is LESS. It needs Ruby. I haven't used it yet but it's definitely worth a look.
A more primitive way to do this would be using a server-side scripting language like PHP.
You would define constants in PHP like so:
define ("MYBLUE", "#33CC99");
and then outputting the value where needed using <?=MYBLUE;?>
Big downside: To do this in external css and js files, you would obviously have to have them parsed by the PHP interpreter, which is not good performance wise if you have a lot of visitors. For a low-traffic site, it probably doesn't matter.
Yes, this is impossible. You could, however, write your own CSS preprocessor (or use one of the existing ones out there), for instance with PHP. The big downside is that you would have to output the colorcode on your whole site with PHP and your scripts would look like
tag.style.backgroundColor = <? echo $myblue; ?>
and likewise in CSS
.someClass {
background-color: <? echo $myblue ?>
}
or something similar. And that isn't really nice either. Of course you could use any server sided script language of your choice. As far as I can judge, this is the only possibility to use a color-constant throughout a whole website.
You could have a look at some processors:
http://cssp.codeplex.com/
http://www.shauninman.com/archive/2007/06/27/css_server_side_pre_processor
http://icant.co.uk/articles/cssconstants/
You may look at HAML+SASS. Though you cannot define variables for all three languages at once, these two can make writing HTML+CSS much easier.
How I would approach this is to make a class in my CSS.
.color_class {color: #33CC99;}
Then call it in my HTML
<td class="color_class" />
You can assign multiple classes to an HTML element.
In the JS, just name the class
document.getElementById('id').className = 'color_class';
Of course you can play with how you want to select your element. A JS library probably has even easier methods for assigning CSS classes.
To achieve this with out using any dynamic CSS (e.g. serving a PHP file with content-type text/css), your best bet is to separate out the places where you define the 'theme'.
<script type="text/javascript">
var theme = '#003366';
</script>
Then you can use a JavaScript file to write out styles based on the themes.
However, if you are able to use a CSS pre-processor, go with that. You'll have much more flexibility and the code will be easier to maintain. I almost always use a PHP or JSP page for CSS.
As other users have noted you can't do this in straight HTML, JS or CSS unless you pass all HTML, JS and CSS content via a CGI/PHP/ASP script - which isn't actually a bad approach as it's easy to maintain.
If you use a query string in the reference to included CSS / JS files - e.g. '/css/stylesheet.php?timestamp=2010-01-01+00:00:00', then almost all clients will aggressively cache your CSS/JS files, negating any impact on load parsing them in a scripting language may have (though unless the site is likely to be particularly busy I wouldn't be too connected about that).
If you are using Apache (which is likely), an alternative approach would be do use something like mod_set to re-write all HTML, JS and CSS files on the fly for you. This may be more difficult to support if you are not familiar with configuring Apache (or are using another web server).
With regard to tag naming:
With either approach I strong suggest using a clear tagging system to denote your dynamic variables (e.g. %MyBlue%) and to consider having variables names be representative (e.g. %HeadingBackgroundColor%, %FontColor%, even if both are set to %MyBlue%), as that can prevent things getting hairy later on (when you discover that changing one value has intended consequences).
Using more representative names may seem unnecessarily verbose at first glance, but it causes problems in many cases because colours end up clash in unintended ways when they are significantly different from the original scheme (this is true of a lot of mainstream software which is skinnable - because the author made the assumption that %value1% and %value2% would always go together and so would %value1% and %value3% - meaning in effect the options for themeing are severely limited by an unintended dependancy).
I do this at build time by running my CSS files through Freemarker.
I am not sure of your end goal. If it is to allow selection of one of several themes for a web page, you could simply have multiple CSS files, and a cookie/session variable/database store of the user's prefered style sheet. Then you could just do
<link rel=<? echo stylepref; ?> type='text/css'>
or something along those lines
If you want to be able to completely customize the site, then one of the above answers would be needed.
There's no concept of 'variables' in CSS, but I'd strongly recommend not doing what you're doing. there's no good reason that you can't define all your style information in your CSS sheet as CSS classes. If you do that, and then just apply said classes in html and javascript, that's one major load off in terms of copying and pasting.
Second, remember that you can define more than one CSS class for an element, e.g.
<div class='blue-text white-background'>my content</div>
You can then define those independantly in CSS, a la:
.blue-text { color : Blue; }
.white-background { background-color: white;}
and you can even create rules that only take effect when both are applyed:
.blue-text.white-background { color : AliceBlue; }
If you want to have the color choices dynamically generated, the only real way to do that is as others have suggested, which is either preprocess your files before deployment, or have the CSS dynamically generated and served by your language of choice.
In pure client side CSS grouping selectors allows you to put the same color on many different elements:
p, .red, #sub, div a:link { color: #f00; }
Using VS2008 and ASP.NET 3.5 (or VS 2010 / .NET 4.0?), how can I include a bit of dynamic ASP.NET server-side code in mostly-static JavaScript and CSS files?
I want to do this to avoid cloning entire JS or CSS files to vary just a small part of them multi-tenant sites. Later, I want to extend the solution to handle localization inside javascript/CSS, dynamic debugging/tracing support, and other cool things you can get by injecting stuff dynamically into JavaScript and CSS.
The hard part is that I don't want to lose all the cool things you get with static files, for example:
JS/CSS code coloring and intellisense
CSS-class "go to definition" support in the IDE
automatic HTTP caching headers based on date of underlying file
automatic compression by IIS
The server-side goodness of static files (e.g. headers/compression) can be faked via an HttpHandler, but retaining IDE goodness (intellisense/coloring/etc) has me stumped.
An ideal solution would meet the following requirements:
VS IDE provides JS/CSS intellisense and code coloring. Giving up server-code intellisense is OK since server code is usually simple in these files.
"go to defintion" still works for CSS classes (just like in static CSS files)
send HTTP caching headers, varying by modified date of the underlying file.
support HTTP compression like other static files
support <%= %> and <script runat=server> code blocks
URL paths (at least the ones that HTTP clients see) end with .JS or .CSS (not .ASPX). Optionally, I can use querystring or PathInfo to parameterize (e.g. choosing a locale), although in most cases I'll use vdirs for this. Caching should vary for different querystrings.
So far the best (hacky) solution I've come up with is this:
Switch the underlying CSS or JS files to be .ASPX files (e.g. foo.css.aspx or foo.js.aspx). Embed the underlying static content in a STYLE element (for CSS) or a SCRIPT element (for JS). This enables JS/CSS intellisense as well as allowing inline or runat=server code blocks.
Write an HttpHandler which:
looks at the URL and adds .aspx to know the right underlying ASPX to call
uses System.Net.HttpWebRequest to call that URL
strips out the containing STYLE or SCRIPT tags, leaving only the CSS or JS
adds the appropriate headers (caching, content type, etc.)
compresses the response if the client suports compression
Map *.CSS and *.JS to my handler.
(if IIS6) Ensure .JS and .CSS file extensions are mapped to ASP.NET
I'm already using a modified version of Darick_c's HttpCompression Module which handles almost all of above for me, so modifying it to support the solution above won't be too hard.
But my solution is hacky. I was wondering if anyone has a more lightweight approach for this problem which doesn't lose Visual Studio's static-file goodness.
I know I can also hack up a client-side-only solution where I split all JS and CSS into "vary" and "won't vary" files, but there's a performance and maintenance overhead to this kind of solution that I'd like to avoid. I really want a server-side solution here so I can maintain one file on the server, not N+1 files.
I've not tried VS10/.NET 4.0 yet, but I'm open to a Dev10/.net4 solution if that's the best way to make this scenario work.
Thanks!
I have handled a similar problem by having a master page output a dynamic generated JSON object in the footer of each page.
I needed to have my js popup login dialog box support localization. So using JSON.NET for serialization, I created a public key/value collection property of the master page that pages could access in order place key/values into such as phrase key/localized phrase pairs. The master page then renders a dynamic JSON object that holds these values so that static js files could reference these dynamic values.
For the js login box I have the masterpage set the localized values. This made sense because the masterpage also includes the login.js file.
I do commend you on your concern over the number of http requests being made from the client and the payload being returned. Too many people I know and work with overlook those easy optimizations. However, any time I run into the same issue you're having (which is actually quite often), I have found I've usually either taken a wrong turn somewhere or am trying to solve the problem the wrong way.
As far as your JS question goes, I think Frank Schwieterman in the comments above is correct. I'd be looking at ways to expose the dynamic parts of your JS through setters. A really basic example would be if you have want to display a customized welcome message to users on login. In your JS file, you can have a setMessage(message) method exposed. That method would then be called by the page including the script. As a result, you'd have something like:
<body onLoad="setMessage('Welcome' + <%= user.FirstName %>);">
This can obviously be expanded by passing objects or methods into the static JS file to allow you the functionality you desire.
In response to the CSS question, I think you can gain a lot from the approach Shawn Steward from the comments makes a good point. You can define certain static parts of your CSS in the base file and then redefine the parts you want to change in other files. As a result, you can then dictate the look of your website by which files you're including. Also, since you don't want to take the hit for extra http requests (keep in mind, if you set those files to be cached for a week, month, etc. it's a one time request), you can do something like combining the CSS files into a single file at compilation or runtime.
Something like the following links may be helpful in pointing you in the right direction:
http://geekswithblogs.net/rashid/archive/2007/07/25/Combine-Multiple-JavaScript-and-CSS-Files-and-Remove-Overheads.aspx
http://www.asp.net/learn/3.5-SP1/video-296.aspx?wwwaspnetrdirset=1
http://dimebrain.com/2008/04/resourceful-asp.html
By utilizing the combining at run or compile time you can gain the best of both world by allowing you to logically separate CSS and JS files, yet also gaining the reduction of payload and requests that comes with compressing and combining files.