Is this an anti-pattern?
For JavaScript and/or CSS code that is repeated between two template files in a Django project, we put that code into a common resource. That resource can then be loaded by a separate request from the client (as is the case with static .js and .css files) or placed in a template file and loaded into the templates that use it server-side, thus avoiding the extra requests that result from creating additional .js or .css files (or increasing the size of existing .js or .css files).
Current practice where I work prefers that latter approach, while I prefer the former. I see the following problems with loading template files on the server side instead of creating additional static files or adding to existing static files:
The number of requests we avoid by loading resource files on the server is insignificant due to caching.
The size of the templates is increased with code that could be cached, meaning that more data is sent over the wire.
This practice spreads CSS and JavaScript code across the project in files that are marked as html templates in spite of their complete lack of actual html text.
When the common code becomes commonly used in more than two pages on our site, we may need to create additional static files (or add to existing ones) anyway.
It is generally a good practice to keep JavaScript separated from the DOM; server-loaded resource files don't do much to encourage this practice.
So, is this an anti-pattern we should avoid, or is it a best practice, and why?
My 2 cents on the issue
Performance wise:
If the JS is important for your landing page rendering, inline it as template.
Otherwise I would generally vote for your way (external JS file) maybe using async, and of course putting the link at the end of the page.
But it some cases like small size scripts, the inline approach can make sense.
Related
I'm thinking through ways to speed up a website I'm developing. I know socket connections are expensive, so I was thinking... Is there any downside to including css and javascript code in the actual html/php source code as opposed to linking to it?
It seems that instead of making 10 calls to various files I could simply put all of the code in the html source code and not have any socket calls to external files?
I know I could put everything into 1 javascript file and call that, but that would still create a socket call.
I realize this is probably not going to make much difference and might just be a thought exercise, but is there any real downside to just inlining the code?
Different resources (i.e. HTML, CSS, JS, images ...) do not necessarily require a new socket connection. With HTTP/1.1 the same connection is usually used for multiple resources (but only after each other) and with HTTP/2 multiple resources can be loaded in parallel over the same TCP connection. Thus instead of trying to optimize delivery by combining HTML, JS, CSS into a single file it would be possible to optimize the transport instead by using HTTP/2.
Apart from that often resources like script, CSS and images are shared between HTML pages. In this case serving the same script etc again and again would just be wasteful. Proper caching instead enables reuse of shared resources between the pages.
And finally, inline script is considered a security problem - just look for Cross Site Scripting. Having the script separated from the content allows the use of a strict Content Security Policy which prevents such attacks.
It depends on different circumstances. For example (size of your js file).
If your js file size is large and having lots of codes then you should consider linking as there are many advantages -
(i) It can be cached by the browser locally so that on next visit of the user, your website will load faster.
If your js file size is very small consider embedding it into HTML as it has many advantage too -
(i) There will be less request on your server.
(ii) If you want some variables to be assigned dynamically you should embed js in HTML because it cannot be done with linked js file.
and so on...
so, I understand the process of minifying / concatenating files but if I am not mistaken, please correct, is that there is an assumption of same files per page.
I run a site in which various pages bring in different css and different JS. As such, how can I both minify AND concatenate these files on a per page basis?
I was thinking, on any particular page - minify and bundle the css/js on page request.
1. Backend code reads in the files - css / js.
2. Backend code minifies and concatenates the files, writes these files to a dir.
3. Subsequent requests will use this newly written file.
Of course, the problem arises in that the "homepage" might have site.css and site.js - those might get minified and concatenated with other misc files on that page. NOW, if I go to the "product page"... those files ( site.js and site.css ) will also be there, but now they are paired with "other product page" js / css files. So, it seems that we can't really "create" a new combined file.. as there will be a ton of duplication of same files across the site.
What are you thoughts, gameplan for concatenating/minifying files when each page brings in a different set ( thought can also contain same js/css files ) as other pages?
I've looked into common programs YUI etc.. but they don't seem to address my particular use case.
I'm not sure you need to worry about concatenating every single script on each page since you'll end up having lots of things cached. For example, if you have site.js and site.css minified and they are common on every page, then you don't need to worry about some permutation that includes them in the additional minification and concatenation you proceed to do on each page. Does that make sense?
On the other hand, depending on how big these files are, a potential solution is to minify and concatenate everything for the entire site and send that down once, knowing that the parts that are not used didn't cost that much in additional bandwidth over the cost of making an entirely new request to the server. I'm aware of at least a handful of companies that do this simply because the overall weight of the scripts from page to page isn't significant and they end up needing to make fewer requests from the client, resulting in faster page loads and an easier load on the server.
Just curious about the current trend to put client-side templates for single-page Java applications in script tags in your HTML file. Seems like an interesting approach, but is this considered a best practice (or at least a better practice)? I tried to come up with a list of advantages and disadvantages, but the list of bad seems to outweigh the good.
So the way I see it is this:
Advantages:
Only one request to get all templates vs. an individual async request for each template file.
Disadvantages:
Creates a potential merge troublespot / bottleneck file if all templates are in one location
A bit cumbersome to edit templates all in one file
A bit cumbersome to find the template you need vs. using a keyboard shortcut to open file.
Have to wait until the DOM is ready before doing anything with a template.
It also seems that with having them in script tags, you can precompile and cache your templates so you're only querying the DOM once to get each template. However, couldn't you achieve the same effect using AMD / Require and a require/text! or dojo/text!? In the latter instance, you'd be lazily loading each template only once. You could then cache it and precompile it at that point.
I just am struggling to see the many advantages of templates in script tags. Am I missing something?
IMHO it really comes down to how many templates you have. When your site is first starting out and you don't have a lot of templates, keeping them all in script tags on a single HTML page makes a lot of sense.
However, as your number of templates grows, that soon becomes unwieldy; before long you're using server-side logic to concatenate a bunch of separate template files in to your master HTML file, and at that point I think it makes perfect sense to start considering other approaches.
Personally my company's codebase started out with script tags in an HTML file, but as we've since grown (and started using require) and now now we have tens if not hundreds of .handlebars (or more commonly, .hbs) files for all of our templates. We bring these in to our Javascript using Alex Sexton's HBS plug-in (https://github.com/SlexAxton/require-handlebars-plugin) for require, and that works great because:
we get to use our standard require system for our templates
templates get compiled to a single compressed JS file when we use the require optimizer
we can configure our IDEs to treat .handlebars files as HTML, giving us the appropriate syntax coloring and such when we edit them
I'm not sure which templating system you're using, but if you're using Handlebars and already using Require then the HBS plug-in is a great way to. If you use a different templating system you likely can find a similar plug-in for Require (if that system is popular enough), or even write your own using the HBS one as a basis.
For anyone with a decent number of templates, I think a system like that (especially for anyone already using Require) makes a whole lot more sense than script tags.
If I understand you correctly, you have some number of client-side templates you want to use, but you would like to separate them into individual files on the server side. When you have a lot of such templates, there is some obvious engineering advantages to such an approach.
You might consider using JSONP. With a half-decent handler on the server side, you get the benefits you're looking for:
Separate file for each template
Easy inclusion into your HTML pages.
The ability to assign each template to a variable, or send it through a compilation function as soon as it is received by the client.
Cache templates on the client side, so they don't have to be reloaded for every page.
Compatibility with caching proxies
The only part of the JSONP implementation that is non-trivial is the caching properties. You need to make sure your server-side controller that receives the request understands conditional GETs, how to send 304 responses, and sets caching headers properly.
If you aren't familiar with the technique, you might take a look at the JSONP wikipedia entry.
In our HTML page, we have a list of tags to load in many (small) JavaScript source files.
For deployment we plan to concatenate the individual JavaScript files into one bundle which will be included in the HTML page, to save on 'expensive' HTTP requests.
But would it be even more beneficial, to just write all the JavaScript directly into the HTML file, in an in-line Javascript tag?
If the JavaScript code changes on every request ("tags"?), then yes, it's beneficial.
Otherwise: No, because the browser will not be able to cache the JS files.
the best way would be to concatenate them but don't put them directly into you html-file. that way the js-file can be cached independently from the (probably) changing html-source.
A file is better than writing the whole stuff into the HTML, as you can cache the javascript file coming from your server, but unless you cache all .html files, you won't get this benefit (i.e. browsers have to keep redownloading all the inline scripts inside your html files)
But would it be even more beneficial, to just write all the JavaScript directly into the HTML file, in an in-line Javascript tag?
No! You would increase the size of every request and destroy cacheability. One big (but external) JS file is the way to go.
Make sure the JS file is emitting the proper caching headers, and it will be loaded only once per client. Unless your JS is exceedingly small (and your description doesn't sound so), that's pretty much the optimum.
I'd suggest that you compile all your javascript into one file and load it with one <script> tag. Yes, HTTP requests take some time, and browsers limit number of concurrent requests (to one domain).
I wouldn't put all javascript in the HTML, because this is mixing logic and representation, prevents caching (of javascript), etc. Avoid this.
This is the general rule I follow: separate content that changes often from content that changes rarely. This way static content will be cached efficiently. And you can optimize "fluid" content (gzip, minify, etc.) so that it takes less time to load.
I'm assuming that you mean 'embed inside a <script> block' rather than in 'on*' attributes inside the HTML elements. If that's not the case, the answer is a definite no - 'on*' attributes are harder to maintain, and typically bad for accessibility.
Normally the answer is no, because although the user's first request will be more expensive if it has to get external resources, those resources will be cached so future requests will be cheaper. If you embed everything, the user has to load them every time they load the page.
So it depends on a few things, the most important of which are probably:
Are users browsing multiple pages? Will they return? If the answer to both questions is 'no', then there is no benefit from caching, so embedded JavaScript can be quicker.
Is the JavaScript static? If it's dynamic - as in, changes on every page load, then again, caching is irrelevant. You could probably improve your JavaScript architecture to separate the static bits from the dynamic.
You can mix the JavaScript so that static JavaScript is linked, while dynamic or page-specific JavaScript is embedded. This is especially useful with libraries - it may already be cached in the client from another site, but if not, you're still loading from a CDN like Google, so it's very quick.
I wouldn't have thought so.
I always just include files and try to keep my base html looking as clean as possible.
Die hards will say don't do it, separate content from styles and scripting, and I agree. But if its not a lot of JS, you may as well save on any additional HTTP requests. Yes, the browser won't cache it, but that's because it won't need to. And on an SEO basis, Page ranking is improved with faster page load, determined possibly on first visit, not after a cache.
Although it is always recommended to put JavaScript and CSS code into appropriate files (as .js and .css), most of major websites (like Amazon, facebook, etc.) put a significant part of their JavaScript and CSS code directly within the main HTML page.
Where is the best choice?
Place your .js in multiple files, then package, minify and gzip that into one file.
Keep your HTML into multiple seperate files.
Place your .css in multiple files, then package, minify and gzip that into one file.
Then you simply send one css file and one js file to the client to be cached.
You do not inline them with your HTML.
If you inline them then any change to the css or html or js forces to user to download all three again.
The main reason major websites have js & cs in their files, is because major websites code rot. Major companies don't uphold standards and best practices, they just hack it until it works then say "why waste money on our website, it works doesn't it?".
Don't look at examples of live websites, because 99% of all examples on the internet show bad practices.
Also for the love of god, Separation of concerns please. You should never ever use inline javascript or inline css in html pages.
http://developer.yahoo.com/performance/rules.html#external
Yahoo (even though they have many inline styles and scripts), recommends making them external. I believe google page speed used to (or still does?) do the same as well.
It's really a logical thing to have them separate. There are so many benefits to keeping CSS and JS separate to the HTML. Things like logical code management, caching of those pages, lower page size (would you rather a ~200ms request for a 400kb cached resource, or a 4000ms delay from having to download that data on every page?), SEO options (less crap for google to look through when scripts/styles are external), easier to minify external scripts (online tools etc), can load them synchronously from different servers....
That should be your primary objective in any website. All styles that make up your whole website should be in the one file (or files for each page, then merged and minified when updated), the same for javascript.
In the real world (not doing a project for yourself, doing one for a client or stakeholder that wants results), the only time where it doesn't make sense to load in another javascript resource or another stylesheet (and thus use inline styles/javascript) is if there's some kind of dynamic information that is on a kind of per-user, per-session or per-time-period that can't be accomplished as simply any other way. Example: when my website has a promotion, we dump a script tag with a small JSON object of information. Because we don't minify and merge multiple files, it makes more sense to just include it in the page. Sure there are other ways to do this, but it costs $20 to do that, whereas it could cost > $100 to do it another way.
Perhaps Amazon/Facebook/Google etc use so much inline code is so their servers aren't taxed so much. I'm not too sure on the benchmarking between requesting a 1MB file in one hit or requesting 10 100KB files (presuming 1MB/10 = 100KB for examples' sake), but what would be faster? Potentially the 1MB file, BUT smaller requests can be loaded synchronously, meaning each one of those 10 requests could come from a separate server/domain potentially, thus reducing overall load time.
Further, google homepages for example seem to dump a JSON array of information for the widgets, presumably because it compiles all that information from various sources, minifies it, caches it, then puts in on the page, then the javascript functions build the layout (client side processing power rather than server-side).
An interesting investigation might be whether they include various .css files regardless of the style blocks you're also seeing. Perhaps it's overhead or perhaps it's convenience.
I've found that while working with different styles of interface developer (and content deployers) that convenience/authority often wins in the face of deadlines and "getting the job done". In a project of a large scale there could be factors involved like "No, you ain't touching our stylesheets", or perhaps if there isn't a stylesheet using an http request already then convenience has won a battle against good practice.
If your css and javascript code is for a global usage, then it is best to put them into appropriate files.
Otherwise, if the code is used just by a certain page, like the home page, put them directly into html is acceptable, and is good for maintenance.
Our team keeps it all seperate. All resources like this goes into a folder called _Content.
CSS goes into _Content/css/xxx.js
JS goes into _Content/js/lib/xxx.js (For all the library packages)
Custom page events and functions get called from the page, but are put into a main JS file in _Content/js/Main.js
Images will go into the same place under _Content/images/xxx.x
This is just how we lay it out as it keeps the HTML markup as it should be, for markup.
I think putting css and js into the main html makes the page loads fast.