cookieless domain to serve css and js - way to organize code? - javascript

I would like to configure my environment to serve css and javascript files from static.example.com instead of example.com/static.
The second has the convenience that I can code my html pages to load the css and javascript files relatively eg "static/reset.css" independent of the actual domain.
Is there a good practice to avoid altering all my source files whenever I change
static.example.com to static.otherexample.com
as I would have to rewrite all my HTML source files importing css and javascript?

Use some kind of configurable prefix to include js and css files. Depending on the technology you're using, it is helpful to have some kind of helper method for this. In ASP.NET MVC, I use some custom method like CSS.Add("reset.css"), which knows the path and URL.
The js files should not really care where they are loaded from. As for css, it's important to know that relative URLs in CSS are interpreted as relative to the URL the CSS was loaded from, not relative to the URL the page was loaded from. So make sure you understand that background-image: url('/images/img1.png') would also load from the static page (which is usually a good thing).
The better way
It's best practice to compress, minify and merge all of the CSS / js files. Therefore, you should only have a very small number of files (one js, one css) to keep the number of requests low. The inclusion of these files would happen on the server, so the URLs don't matter. To implement this, you will need some kind of helper method (and a lot of compression logic, but there are libraries for all this).
For ASP.NET MVC there is SquishIt, but I'm sure there are plenty of tools for various environments.

How is the html being generated?
You could use a config value or constant, and use that value for the domain portion of the url for any of the static assets.

You can always do a trick on the server, i.e. all your urls in HTML could be relative to /static, but once your server receive request, it can "change" the route and get files from static.current-domain.com instead of current-domain.com/static

Related

Dynamically load JS/CSS per template with Meteor

I understand a couple questions (i.e. this) of this nature have already been posted, however no solid solution has been found. From what it seems, Meteor currently lacks of the ability to dynamically load/render different UI JavaScript (i.e. uilang) or CSS files per template. In my application, I have templates that require specific JS libraries and CSS as oppose to other templates.
For example:
user.html requires -> uilang.js, user_ui_code.js, userstyle.css
admin.html requires -> uilang.js, admin_ui_code.js, admin_style.css
I would need each js/css file to render/load depending on which route gets requested (i.e. example.com/user or example.com/admin), for things like different background-colors, transitions, etc. Meteor documentation states:
Files in /public are served to the client as-is. Use this to store assets such as images. For example, if you have an image located at /public/background.png, you can include it in your HTML with or in your CSS with background-image: url(/background.png). Note that /public is not part of the image URL.
So you would think that putting all your js/css/images assets in public and calling the needed files statically in head would solve the problem. Instead, it seems that the JS (CSS as well) files get concatenated and it all runs at the same time regardless of which route you are on, thus overlapping code. I'm not sure if I am missing something blatantly obvious or is this an actual issue in Meteor?
Thanks for any help.
Meteor doesn't yet support lazy/on demand loading of resources. The feature is on the roadmap as "incremental loading".
In the meantime, have a look at numtel:publicsources and numtel:privatesources, which let you create bundles for lazy loading resources, with or without authentication.

HTML + JS + CSS converter

I have a HTML file with JS (jQuery) and CSS. I want a converter that converts all the files, minimizes it and just puts it all in a index.html for example. Google seems to be using this, they have no external files, not even the image, everything is just in one file and I'm sure pre-compiled before release.
Also is this a good idea?
This is not a good idea, in general.
Splitting out your CSS and JavaScript files means that they can be cached independently. You will likely be using a common CSS and JavaScript across many pages. If you don't allow those to be cached, and instead store them in each page, then the user is effectively downloading a new copy of those files for every page they visit.
Now, it is a good idea to served minified versions of these files. Also make sure to add gzip or deflate transfer encoding so that they are compressed. Text compresses nicely... usually around a ratio of 1/8.
(I should note that there has been one occasion where I have loaded everything into a single file. I was working on a single-page web application for the Nintendo Wii, which had no caching capability at all. This is about the only instance where putting everything into a single file made sense. Even then, it is only worth the effort if you automate it server-side.)
I don't recommend to concat CSS with JS.
Just put your css at the top of the page and js at the bottom.
To minify your CSS and JS you have to use gruntjs
Also I recommend you to read this article: Front-end performance for web designers and front-end developers
If your intention is to load the pages faster:
For images: try to use image sprites or images from different domains because browsers love downloading resources from different domains instead of just one domain.
For scripts as well as css: use online minifiers that can reduce white-spaces and reduce the size (if you are on a web hosting, your host may be already compressing the scripts for you using gzip etc)
For landing pages like index pages: If you have less styles then try inserting them inside the <style></style> tag, this will make the page load very fast, Facebook mobile does it that way.
If it wasn't a good idea, google wasn't be using it!
If you put everything in single file, you'll get less HTTP requests when the browser will check if the newer version of file is available.
You also get read of the problem that some resources are not refreshed, which is the headache for 'normal' developers, but it's a disaster in AJAX applications.
I don't know of any publicly available tool doing it all, surely Google is having its own. Note also that, for example in GWT, many such embedding was done by compiler.
What you can do is to search for:
CSS image embedder - for encoding images into CSS
CSS and JS minifier - for building single CSS/JS and minimizing it
And you need some simple tool that will embed it into HTML.

Ext JS best practice for classes ends up with too many .js files. What about performance?

In order to achieve modularity & reuse of my custom elements / classes (extended from Ext JS classes / widgets), I am following the approach suggested in The Class System. Since I'm using most of the simple & complex widgets as well as layout containers, I am likely to end up with scores of .js files with 3 to 4 levels of namespace hierarchy (and therefore folder structure).
I am a little nervous with this approach because traditionally (with raw JavaScript) I have tried to minimize the no. of .js files. Since my page may use many of these custom elements, it will call quite a few of these .js files. Am I right to assume that this will create a huge performance bottleneck or am I thinking too much?
Next, how can I ensure that the .js files that once requested from the server remain cached in the browser at least for the session? I have observed that the .js files are always requested with a dc attribute, each time with a random number. This doesn't help the situation since all what I am requesting is a class definition file that is not changing with each request. How can I address this?
You need a pre-deploy build step that merges all of your .js files together into a single one for download to the client. (It will also likely minify the resulting file.) Then you can serve a single file with HTTP cache headers.

Include separate CSS and JS files into the header OR all code in one CSS and one JS file?

I'm trying to optimize my website. I have a few plugins to include (jquery plugins with CSS), and my own javascript code.
Now I have the CSS in separate files for different plugins, as I downloaded them. And if I need one on the actual page, I generate code to include that. The same with the JS files. But when it comes to render a complex page with a lot of stuff, 9 CSS files can be called and 7 or 8 JS files, each of which are HTTP requests.
Should I put the CSS into one big file to reduce the number of included CSS files? But then everything will be interpreted by the browser even if the current page doesn't need so much stuff.
I've thought of a third way: generate CSS and JS files with PHP. Then it'll be always one JS and one CSS file, and only with the things which are needed. Or is it an absurd way?
What do you say, which to use to reduce page load time?
It is better to include all CSS in a file and all JS in a file and the minify them using many online services that minify and compress CSS and Javascript. this will reduce the number of http requests as well as volume of data to be downloaded.
If you generate CSS with php then the CSS and JS should be downloaded with every page and generating them takes some time, but if you pack them in one file it downloads once and the browsers caches it.
if your site has many different sections and packing all css in a file makes a huge file then you can pack CSS in two or three file and in each section load the related one.
reducing number of http request is very important.
I think your last solution is the best one.
Generate one js file and one css file from php, and don't forget to minimized/gziped them :)
Here is a very good article about optimization : http://developer.yahoo.com/performance/rules.html
This depends largely on how your users use your page. If most of the users just view one page then it makes sense to only send them the stuff that they need to display that one page (combining everything into as few requests as possible). On the other hand if most of users view multiple pages then it makes sense to send them more than they need so they will already have the CSS&JS on the next page view. But in this case you have to make sure that you are always generating the same CSS&JS with the same URI, so that the browser will not re-download the same content under a different name. You also have to setup proper HTTP caching.
What I usually do is split JS/CSS in two parts. Every page has a "common.css" and "common.js", which has stuff that every page needs (header/footer/... styles for CSS, and then jquery/common js/... for JS). Then every subpage has it's own JS&CSS that has just the stuff you need for that page (if required).
For me, the best way is somewhere in the middle - for CSS files, you better grab them all, join and compress to one file. For JS code - make for example 3+ files: one with compressed and joined external libs, one with your common stuff, and maybe next files for each bigger section - but I dont think its needed. Maybe splitting your JS code on part needed before user login, and after user login.
Remember to minify and consider asynch loading (with LAB.js for example).
Oh, and this php script... I dont think it is good idea - better use/write some script which joins and minifies your statics on compile (or deploy, or even run by hand), so there is no need to generate everythin over and over again.

Django : Is it a good idea to generate JS dynamically?

When I write my JS files for a Django project, of course I do some AJAX calls, and for the moment the urls for those calls are hard-coded (which is very ugly).
I was thinking of having the JS files served by django (instead of Apache), so I could take advantage of the template tags ({% url %} !!!).
Is there a reason why I shouldn't do this ?
Or is there a right way to do this ?
(I can give a least one : it will consume a lot of time resending JS files that haven't changed. What would be great is to have an application that generates files when restarting django server, and serves them statically after !)
I would go for a hybrid technique. Serve most of your javascript statically. But in your Django template, have a <script> block that defines various global variables, which are generated by the server-side code - url is a good example. Then your static JS can refer to the variables that are generated in the dynamic code.
I searched deeper in those asset manager applications from djangopackages, have found out that django-mediagenerator provides that feature, even if it is not well documented : you can generate your js or css files as django templates, and then serve them statically (they are also bundled, and caching is managed etc ... so two birds with one stone + it is really easy to set-up !).
In order to have JS files generated as django templates (after having set-up django-mediagenerator), just add the filter :
ROOT_MEDIA_FILTERS = {
'js': 'mediagenerator.filters.template.Template',
}
in your settings.
Dynamically generating Javascript on your server can be a tremendously powerful tool and I've experienced both it's upside and downside in my projects.
In general you want to keep as much as possible static to minimize the work to be done on every request. This includes having the browser cache as much as possible, which might become a problem in your case.
What I usually do is to have a block in the header in my base template. In templates that need to do custom javascript that is only known at runtime (customization based on logged in user, for example), I add it to the block. Here I can dynamically generate javascript that I know won't be cached so I can make some assumptions. The downside is more complexity.
If what you need are just pointing to urls, or have some simple configuration, etc, then I would suggest creating a view that will return a Javascript file with these settings. You can set the correct headers(Etag, Cache-Control, etc) so the browser will cache the file for some reasonable time. When you upgrade your code, make sure the Etag will change.
In the code that needs to use the configuration, you need to always check that the variable you are looking for is actually defined otherwise you will run into problems that are hard to debug when for some reason the configuration javascript is not loaded correctly.
The .js that gets sent to the browser would vary. That could make debugging more cumbersome. Maybe not a problem but something to potentially consider...
Nowadays, the best way to do this is to use Django.js
Here is the doc where they talk about the URL reversing: http://djangojs.readthedocs.org/en/0.8.1/djangojs.html#reverse-urls

Categories