Best practice to combine JS files [closed] - javascript

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.

Related

How can I protect my application code? [closed]

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 6 years ago.
Improve this question
I am building a web application for a company so they can test the app on a control group of people to see if they would like to try funding the app. Funding beforehand is not an option, however I would like to keep the code somewhat private, so that someone from an IT team can't just easily download all the app files and claim it as theirs. I have researched a little but also found little on what can be done to protect the files for the app which are written in javascript, html, css, ect. basic web development languages. i was just curious if anyone knew of a way to somehow protect these files if it is even possible. I'm not against sharing my code, however for a business opportunity I prefer that it remain private for the time being.
This question has been answered before: How can I obfuscate (protect) JavaScript?
But anyway, here's my take on the question:
You don't need to protect your HTML/CSS code, unless that aspect of the app is what is so proprietary. If that is so, obfuscate your code (there are many websites online that will do this for you).
From the information you gave me, I can infer that it's not the styling or the UI you want to protect, it's the application's logic. In that case, you can obfuscate and then minify the JS code such that it's very hard to deconstruct (although some web browsers do pretty-print the code). To see an example of this, go to Google, open the dev tools, and look at any JS file under the Sources.
I also saw another interpretation to your question. If you meant "to protect the application from being downloaded and then reuploaded", that sadly isn't possible with web apps (unless you explicitly check the domain that the app is running on and restrict the app from running on domains other than yours).
An implementation of the domain-protection would look something like this:
if (window.location.hostname !== "yourwebsite.com") {
alert("Invalid domain, redirecting to official app...");
document.location = "http://www.yourwebsite.com/app/";
}
After adding this protection, you can stop it from being removed by minifying and obfuscating the JS code.
For the css and Js a lot of people use minification. This makes your code really hard to read and finding the business logic in your code. As for the HTML you could uglify it. There is no real way to hide HTML,CSS, JS in your browser because the browser dev tools would reveal all of the code. There are only ways to make it unreadable.
JS minification tool : https://javascript-minifier.com/
Css minification tool : https://cssminifier.com/
https://developers.google.com/speed/docs/insights/MinifyResources

Why would one not put CSS directly into HTML? [closed]

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.

When is namespacing appropriate in JavaScript? [closed]

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

Why write modular javascript? [closed]

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.

Is it possible to use muliple AJAX libraries on one page? [closed]

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 am just curious. There are many ready-to-use AJAX libraries out there like Mootools, Scriptaculuos, Prototype, YUI etc
My question is, is it possible to combine them? If I download all the code and put them on the same page, will it cause errors?
Which open source AJAX library would you recommend for a beginner?
If you're using Java on the back end, the ZK framework claims to provide full AJAX capabilities, i.e. no need to mix and match a bunch of different libraries. From the testing I've done so far, they seem to be right.
Of course, but like anytime you combine frameworks, you'll find you sometimes have to write your own glue code. For a beginner, it may be simpler to use just one.
It depends on the choice of frameworks you use. If they try to define the same variables then one is going to overwrite parts of the other. jQuery avoids this by defining the aliasing the core function so it has two names and YUI avoids it by not having a blasted dollar function in the first place.
Libraries tend to be relatively large, so you should probably avoid using multiple ones on grounds of bloat rather then anything else.
It is rare that using two different libraries is useful - the main reason for it is wanting to use multiple third party modules that depend on different libraries. In that circumstance, I would try to find alternatives that use the chosen library.
What opensource ajax code you using?
YUI usually. It is robust, well tested, well documented and powerful - although the initial part of learning curve is a little steeper then some of the others.
It does it a disservice to call it "ajax code" though - Ajax is a very small part of any of these libraries.
What would you recommend to ajax
beginner?
YUI.
What ajax features that can impress people?
That depends on who the people are. A lot of people will be impressed by being able to quickly produce slidey, fading, spinning animation effects ... but they aren't all that useful. A good event handling system doesn't do anything that will impress a lay person, but it will make like a lot easier for the programmer.
I recommend you to use the jQuery framework, because in my opinion has one of the best and easiest to understand implementation of AJAX.
An example:
jQuery.post('thescript.php', parametersInJson, function(response){
alert('The server response: '+response);
});
yes you can but you might run into some trouble (you might need to override the $ function...)
and i do recommend jQuery

Categories

Resources