Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Situation:
I have a website that is served dynamically. In order to optimize the website's speed, all the CSS and javascript is put directly into the HTML document.
Pros:
It cuts back on web requests
Less files need to be downloaded
Faster webpage download
Cons:
Possible caching issue
So apart from the caching part, is there a reason not to do this?
If you have your CSS in a separate stylesheet file your site will be more maintainable, even if your CSS is inserted into the outgoing document by an automated server-side process.
By having your CSS in a separate file you make each page downloaded smaller.
However the benefits of "less files need to be downloaded" and "faster webpage download" are false. With a separate CSS file (with an aggressive Expires:header) your webpages will load faster compared to in-lining the CSS because the browser won't re-request the stylesheet on every subsequent page request (though the first visit would incur this cost, it really is minor).
CSS was designed for separating content from presentation. The W3Schools maintain that it is a good practice to use html for your structure, and css for styling.
This will make it easier for you. If you are working with large files, it's better to have a separate stylesheet for your css, or better yet, multiple stylesheets. It can be pretty unreadable to have inline styles or style tags in your html document.
Set up both examples on a sub domain, and then test both at tools.pingdom.com
You'll see the differences between the two in how fast they load.
It's just tidier to keep files organised.
Front end users usually won't notice performance increases like that, they will notice when your code has a bug and you are taking forever to fix it because the code is unreadable and hard to debug.
Nice readable code > optimized unreadable code
Quite many factors.
If your application is SPA and uses relatively compact CSS and self-contained scripts then it is better to serve it as single file indeed.
In all other cases you'd better use tools to compare various combinations.
It might be a better question to ask.. why -wouldn't- you? Unless you have a single page, you probably want to use the same styles on every page. So, you don't want to have to write those over and over and over.
You're wasting time adding the CSS to the page (unless you are dynamically generating the CSS as well). I'd think in most cases, you can just put in the link to the CSS in your generated page, and it'll end up in almost all cases (except for the initial page load for a new user) be faster on both the server and client end.
Unless you're generating the CSS at the same time, as well.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to send a link to a client with some work I am doing for them but they are rather informed about IT and that would lead me to think that they know how to copy and paste some HTML and CSS. How would I go about stopping them from seeing the HTML, CSS and JS of the page I want to send them?
Unfortunately this is not effectively done. While it is true that HTML and CSS can be minified there are a large number of free utilities out there that are designed to reverse the minification, or "beautify", whatever you have minified.
There are a range of other methods which are used on occasion but don't really do anything to protect the source from anyone except those who wouldn't care about the source anyway.
Source Code Padding
This is one of the oldest tricks in the book and involves adding a ton of white space before the start of the source so that when the user opens the view source window it appears blank, however almost everyone these days will notice the scroll bars and scroll down the page until they hit the source. This also has the extra negative effect of degrading performance for your site as it substantially increases the amount of data being sent to the client.
No Right Click Scripts
These sorts of scripts prevent the user from right clicking on the page and opening up the page context menu however they are notoriously hard to get working across browsers, annoy users who don't like the native functionality and usability of their browser being altered without permission, and don't make any difference as the source code window can be opened from the top menu.
Javascript "Encryption"
This is a very popular method to suposedly "protect" the source code of the page and involves taking the code and using a custom made function to encrypt the script before pasting it into the html file and then embedding javascript in that file to decrypt the markup at run time. This only works if the end user has javascript enabled and is not effective in protecting the page from other designers and coders as you need to embed decryption javascript in your page which the user can use to reverse your markup and see the plain text markup.
HTML Protection Software
There is software out there which is marketed as protecting HTML and CSS however these protection software packages generally use one of the above methods, and charge you for the privilege of having a false belief your code is actually safe.
Unfortunately the way the internet is designed to work with HTML and CSS this is not possible and won't be without such a drastic shift in the web landscape and the way websites are designed that I personally don't see it ever occuring.
Information sourced from http://www.htmlgoodies.com/beyond/article.php/3875651/Web-Developer-Class-How-to-Hide-your-Source-Code.htm
If your concern is that they'll steal your work, then maybe you shouldn't be working with them.
Also, if you have a good contract in place that specifies who owns the work at which stage of the process, this won't be an issue. In other words, if it's clear that you own the work until it's paid in full, you could sue them if they steal it.
Although it won't stop people stealing your code, you can make it harder to do so using minification - this will remove whitespace and translate variables to harder-to-read names, amongst other things. This will also reduce the footprint of your code, icnreasing the page load speed.
You can't do anything except obfuscate and minify it. There are several utilities to do this if you google it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I always have this questions in mind come to JS optimise, nowadays most people combine all their CSSs into single file by using Less, Sass or others methods. but come to JS i am a bit hesitate on the approach, cause there are plug-in, frameworks and your own code. Just wondering is there a rule or best practice to approach.
so should i combine all my JSs into single JS include plug-in, frameworks, libary and my own code into one or keep them modularized accordingly.
I know it may depend on the size of the project, but what's the measurement and when I should combine all into one or modularize. Is there any rules I should be followed.
Any suggestion are appreciated.
It's generally a good idea to combine and minify your own development JavaScript. Having multiple HTTP requests can slow down load times if there are too many requests (especially if there are multiple small files). Google PageSpeed Insights gives some guidelines on how to do it here.
As #veroxii says, most people end up using a "build" since minifying and combining everything manually would be a huge waste of time. For small sites that I work on that don't really have a built in minification system, I like to use gulpjs along with gulp-uglify and gulp-concat to minify and combine javascript resources.
You have to be careful when combining though because often times, scripts will depend on other scripts. Say you have two scripts that you combined where scriptB depends on scriptA. If the browser loads and runs scriptB before scriptA because it came first in the combined file, then bad things will happen. Either be careful with your script combination or use something like requirejs.
You can't really do much in terms of minification or combination when using a third party script loaded in from a CDN (like jQuery) except use the production script.min.js resource that they provide. You could potentially download their script and throw it into your minification process, but most users are more likely to already have the CDN version cached by their browser.
The biggest thing when it comes to JavaScript is making sure the loading of the scripts don't block the rendering of the page. Most JavaScript is useless without content, so why not let the content load first and then load in the script? Users will see the content first and then interact so it's probably a good idea to load those resources in that order. More on that here. Either put your script tags at the bottom of the page, use the asyncattribute, or use an asynchronous javascript loader like loadJS or requirejs.
Which framework are you using on the server side? Most of the frameworks out there come with an "asset pipeline" already built in or as a plugin.
For instance django has https://django-pipeline.readthedocs.org/en/latest/ and grails has http://grails.org/plugin/asset-pipeline
This does everything you asked about and more. I'm sure there's something similar for whatever you're using on the serving back-end.
Edit: to clarify - I don't think this is something people do manually. They have a tool which does it on the fly or at build/deploy time.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
For a new page I'm working on, I want to make sure I do everything “right” to the best of my ability. I was wondering what the best practices were re. one JS file per page or one file containing everything. I found this question which helped some, but raised more questions.
I pretty much only use JS for three things:
transitioning things on button clicks (showing/hiding panels, etc.),
pre-validating forms, and
AJAX calls.
When I compare my use cases to the namespacing approach, it seems like overkill; I don't really understand why I would need to set up such a complex framework to work with JavaScript. This leaves me with two questions:
For what I'm doing, should I use one JS file per page, or use Irish's namespace technique and a single script import?
What the hell are people using JS for that requires so much structure?
If your pages don't have anything in common, you might use a script file for each page. If you've got a lot of logic common between your pages, you'd probably want to put those common bits into a file of its own and include it wherever you need it.
As for why so much structure is necessary, people are making more and more complex things with JavaScript. Consider Gmail, for example. I'd imagine there's quite a bit of code in there, and without much structure, it would become difficult to maintain quickly.
OK, That page is from 2009 - The way Javascript is used on the web has changed a lot since then.
Now that most web pages contain multiple third-party Javascript files from different sources (and different developers). It makes a lot of sense to encapsulate your code in a custom namespace to prevent your code being overridden by other code using the same variable names, and it isn't any harder than:
Mynamespace= {};
Mynamespace.foo = "bar";
Mynamespace.foobar = function(){
//function body
};
Writing structured Javascript isn't about adding complexity. Writing structured Javascript allows you to encapsulate behaviours and responsibilities into re-useable portions of code that are much easier to test, maintain, re-use and extend.
You don't even need to make the single-file/multiple files judgement. You can use a framework like require.js that compiles all of your separate code files into one single file for deployment.
JavaScript is now officially a first-class language in Visual Studio Its being used to write web-servers, templating systems and even 3d engines.
Welcome to 2013 ;-)
_Pez
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
The benefits of well-factored and modular code, in my understanding are re-usability and organization. Code written in a big chunk all in one file is difficult to read, and re-using small portions of the code requires careful copy-pasting, rather than include statements.
In particular, with regards to Javascript, I came across an example recently that got me thinking about this. A comment was made on SO to the effect that, if you are not including your javascripts conditionally on a page-by-page basis, this "represents a failure to modularize JS code properly". However, from a code re-use and organization point of view, there is no reason to consider what happens at page load time. The code will be just as readable if it is written in a bunch of separate files and then mashed together and minified before being served. The rails asset pipeline, for example, does just this.
When I first encountered the asset pipeline, my mind reeled and I started wondering "how do I make javascripts load only when needed?" I read a few SO questions and an article on the matter, and began to think that maybe I shouldn't worry about what happens to my code after it "compiles".
Is the purpose of writing modular code purely a human-level activity, should we stop worrying about modularity after the code starts running? In the case of Javascript, should we be concerned that our scripts are being mashed together before being included?
I think the one thing that you are not really talking about in this with regards to performance is actual HTML browser download behavior. I believe you have to walk a fine line between only displaying the javascript needed on a page by page basis and leveraging browser caching and download behavior.
For example, say you have 20 different javascript snippets that are going to be used on every page. In this case it is a no-brainer to compile/minify them into a single file, as the fewer files your browser needs to download, the better. This single file would also be able to be cached, that is assuming it is a static file or appearing to be static (via headers sent) if it is dynamically compiled.
Now say of those 20 snippets, 15 are used on every page and the others are used intermittently. Of course you put all 15 of the always used snippets into a single file. But what about the others? In my opinion you need to consider the size and frequency of use of the files. If they are small and used relatively frequently, I might consider putting them into the main file, with the thought that the extra size in the main file is outweighed by the need to have additional request to download the content later. If the code is large, I would tend to only use it where necessary. Of course once it is used, it should remain in cache.
This approach might best be suited for a web application where users are expect to typically have multiple page loads per session. Of course if you are designing an advertising landing pages or seomthing where the user only may see that single page, you might lean on keeping the initial javasciprt download as small as possible and only loading new javascript in as necessary based on user interaction.
Every aspect of this question boils down to "it depends".
Are you writing an enterprise-level application, which results in 80,000 lines of code, when you stuff it all together?
If so, then yes, compilation time is going to be huge, and if you stuff that in the <head> of your document, people are going to feel the wait time.
Even if it's already cached, compile time alone will be palpable.
Are you writing dozens of widgets which might never be seen by an end-user?
Especially on mobile?
If so, then you might want to save them the download/compile time, and instead load your core functionality, and then load extra functionality on-demand, as more studies are showing that the non-technical end-user expects their mobile-internet experience to be similar to their desktop experience, not only in terms of content, but in general wait-times.
Fewer and fewer people are willing to accept 5s-8s for a mobile experience (or a desktop experience on mobile) to get to the point of interactivity, just based on the "well, it's mobile, so it'll take longer" train of thought.
So again, if you've got an 80,000 line application, or a 300kB JS file, or are doing a whole lot of XML parsing, et cetera, prior to load, without offering a separate mobile experience, your stats on mobile are bound to hurt -- especially if you're a media site or a commercial/retail site.
So the correct answer to your question is to say that there is no correct answer to your question, excepting that there are good ideas and bad ideas, based on the target-devices, the intent of the site/application, the demographic, the code-base, the anticipation that users will frequent the site (and thus benefit from cached assets), the frequency of updates to the codebase (having one updated module, with 20 cached modules, versus a fully-invalid 21-module chunk, due to one updated line, with a client-base of 250,000 customers, is a consideration for several reasons)...
...and more...
Figure out what you're doing.
Figure out what you need to do to make that happen.
Figure out how to do it, while providing your customers a good experience.
Know how to combine files.
Know how to load on demand.
Know how to build a light bootstrap, which can intelligently load modules (and/or learn require/AMD).
Use these as tools to offer your users the best experience possible, given what you're trying to accomplish.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
What is the optimal filesize of a JavaScript and CSS files of a websites?
Zero bytes. It sounds facetious, but there's no such thing as an "optimal" file size. The bigger it is, the longer it will take your page to render. How fast is the connection to your web site for your visitors? If it's a video-oriented site, for example, it's probably relatively fast since people with 64 kbps modems aren't going to be trying to stream anything that large. If it's a simple text site displaying information to satellite users in Zimbabwe, it might be quite slow.
So let's imagine that the average speed is 1.5 Mbps. Realistically, halve that to 750 Kbps. That's about 94 KBps. So if your CSS file is 50 KB and your javascript file is 50 KB, it will take a little over one second to download them for your visitor. Is your site highly interactive, with users expected to click around quickly from one thing to another? If so, then that once second delay could be extremely irritating. If not, then it might be perfectly reasonable.
If you find your file size getting too large, you might want to consider looking at some "minifying" utilities; these are utilities that will take your code, replace variable names ("my_descriptive_variable") with shorter names ("a"), remove whitespace and comments, etc. Sometimes these utilities can reduce your code to 10% of what it was before.
Ultimately, though, "optimal" is completely subjective. Try designing minimal script/CSS files, add a bunch of KB of comments to them, and load your page on low-end connections until you consider it too slow. That will give you a pretty good idea of what your upper limit should be.
The smaller your external files the better.
But perhaps more important than having a smaller size is having fewer separate resources, meaning fewer HTTP requests. For example, a single 1MB file often loads faster than ten 100KB files. You're better off when you combine multiple CSS (or JavaScript, image, etc.) files into a single one.
The one thing you really want to take advantage of, though, is cacheing. So put all your shared utilities and styles into one file, minify that, and include it on every page. Most modern browsers will download it only once, and download it quickly (being minified). Then, minify the page-specific ones also and you're done.
The total size of a page while it is being viewed by the user should be approx ~100kb. This makes it easier for the user view and Search Engines to crawl your website.
The concept of "page size" is defined as the sum of the file sizes for all the elements that make up a page, including the defining HTML file as well as all embedded objects (e.g., image files with GIF and JPG pictures). It is possible to get away with page designs that have larger page sizes as long as the HTML file is small and is coded to reduce the browser's rendering time.
Typically your Javascript file should be less than 25kb and your CSS file should be less than 10kb, the smaller the better, these numbers will vary depending on resource and items. Sometimes this is not possible but you can minimize whitespace (spaces, returns and removing comments). Ideally each line should be one style definition in your CSS and your Javascript should be beautified (redundant code removed and code that is used over and over to be put in functions) and minimized to be on one line if possible.
Typically your CSS should be loaded in the head of the page and the JS right before the closing body tag. This is so the page can still load while waiting for the CSS or JS to load. Most browsers and servers will only load about 4 resources from one server at a time. If possible you can seperate your resources over multiple servers/subdomains to create asynchronous loading.
The asynchronous loading applies to all aspects of a webpage; images, CSS, JS, and html. All my knowledge has been collected and learned from working on sites for over 10 years.