I have a ASP.NET MVC 2 project on Visual Studio 2010. I want to be able to use my plain javascript files in debug mode so I can understand what's going on when debugging, but I want to used a minified/compressed version when using release mode.
I was planning to create some extenders to include the js files in each page, something like:
In that extender method I would determine whether I am on debug or release mode and pick the appropiate JS file. The disadvantage here is that I would end up manually compressing/minifying the JS every time I change something.
Is there an automated way to compress/minify and include the JS file when compiling in release mode?
The best option is to compress files by running a post build task from visual studio: Compressing JS files as part of your build process
You might want to take a look at the Yahoo YUI compressor.
You could use a post-build event and the Microsoft AJAX minifier or the YUI Compressor.
I manage a PHP development shop but we do this very same thing. In our development environments, our code is not obfuscated or minified. To push our changes to our live site, I coded a perl script that updates our version control and then invokes the YUI Compressor to minify the JavaScript and CSS before placing it in our live static directories.
As an aside, you may also want to look into merging your CSS and JavaScript on publish as well for added performance. After we minify our static content, we concatenate it into similar files based on purpose. For example, we have about 20 JavaScript files that end up in a file called 'global.js' on our production server. Our code is written such that development environments include all JavaScript files in our js/global/ folder separately, but on production it includes everything in js/global/ as 'js/global.js'. Then, we just iterate through the minified files during publish and concatenate their contents into js/global.js.
The benefit to the merge approach is fewer JavaScript and CSS files for the users to download which means faster page loads. This approach also allows you to split your JavaScript into separate files in your development environment by purpose for easier maintenance.
Related
I've the need to generate some css / javascript at Runtime on my project. After generating this code ( probably with PHP) i need to get the string, minify them and then save the minified file.
I was searching for a tool to do that in Java/Scala, but all the tools i found are for minifying the project files, not plugin to do that on specific files as needed.
I looked at wro4j since it seems it could work that way, but couldn't find how to do that inside the java code and not at build time.
how to do that inside the java code and not at build time
I would recommend the following approach:
Generate the JavaScript and CSS files, unminified
Minify the files using an external tool like yuicompressor
If you don't want to generate the files first, yuicompressor offers a node.js version that can minify JavaScript strings directly. I'm not sure if that would work on CSS strings also.
Given the relative complexity of running node.js within Java, you might want to write a small node.js tcp server that you can send the JavaScript/CSS strings and return them minified. This approach also promises some nice scalability properties in terms of throughput.
I am using jquery fileupload plugin and it has 7-8 js files which it loads.
Now others developers are also working on site and sometime it cause confusion and difficult to find which js file is used where.
So i am thinking if i can combine 7 files in one file so that i can know that thats my file
Try this to compile your javascript file or code.
http://closure-compiler.appspot.com
While possibly overkill in this particular case, it might be worth checking out grunt. It will let you keep your files divided into multiple files for when you are working on them, and as soon as any file change compiling, minifying and combining them into a single/groups of files as desired, while also allowing you to define the load order of your code.
It requires some setup the first time you run it (which you can later use as a template) but greatly improves the process of combining/minifying files, and also has support for processing coffescript and sass among others, as well as writing unit tests for your code.
I use Rake to compile Javascript (and SASS to CSS, as well). It minifies the files in a unique JS. It's written in Ruby, but it's easy to configure and it works very fine.
But if more developers are working on the same code, another good idea I strongly suggest is to to use a SVN (sub-version control system), as TortoiseSVN or Git. This will allow many developers to work on the same source files, without losing any change.
Background: Got a C# project which involves a block of javascript that gets programmatically injected in the web pages displayed by a webbrowser control. However, it is desirable to minify this block of javascript and have it embedded/written-into in a property of the resources-file. I know the minification of javascript is possible. I was just wondering if it's also possible to write the resulting string into a specific property of the resources files using pre-build events.
P.S.: Of course the resulting string can be written into a file which is in turn bound to a resource-property. However I would prefer to avoid something as such, fearing the performance penalty it would impose in runtime (the javascript block gets loaded quite often). If I'm mistaken about this feel free to correct me.
For anyone struggling with similar issues out there, this is the step-by-step approach I have opted for (having run out of alternative solutions) in the context of Visual Studio 2010. The method below handles the minification of javascript files in a uniform way while respect the version control system you might use (by avoiding to generate phantom changes in files hosted by it). Here are the steps:
Install Java and Google's Closure (for javascript minification).
Open the Resources of your project, go to file-resources and create a dummy file-property a-la foo.txt. This should create and include in your project the directory named Resources. You may delete the foo.txt file after this.
Right click the Resources directory and create a javascript file ending in Uniminified.js (for example MyInjectableJavascript.Unminified.js). Edit the properties of this file and make sure that the build action is set to "None". By the way, DO NOT reference this file in the resources.
Now go back to the Resource's file-properties and add a new file-property with the same base-name of the file created above only this time ending in min.js (for example MyInjectableJavascript.min.js).
Go to the .min.js file that was created under the resources directory and turn it into an Embedded Resource.
Now go the properties of your project -> build events and insert the following code:
Pre-Build events (in one line):
call "$(ProjectDir)JavascriptMinificationWithGoogleClosure.bat" "$(ProjectDir)Resources\MyInjectableJavascript.Unminified.js" "$(ProjectDir)Resources\MyInjectableJavascript.min.js"
Post-Build events (two lines):
del "$(ProjectDir)Resources\MyInjectableJavascript.min.js"
call echo. 2> "$(ProjectDir)Resources\MyInjectableJavascript.min.js"
What this does is that it minifies the javascript code before your project is built and after it is build it resets the minified file to a single newline.
Note: The reason we don't delete the minified file all together, is that visual studio will generate an error and will behave very weirdly if the minified file that is referenced by the resources is not found (in my case visual studio deleted Resources.Designer.cs completely out of the blue ... 5 times). By truncating the min.js file it to a single newline you can keep it around and even add it to your version control system without bothering with it ever again.
Under the directory of your project place a file named JavascriptMinificationWithGoogleClosure.bat with the following contents:
"%JAVA_HOME%jre6\bin\java" -jar "%CLOSURE_JS_HOME%compiler.jar" --js %1 --js_output_file %2
Finally, create two environment variables (Right click Computer -> Properties -> Enviroment Variables) named JAVA_HOME and CLOSURE_JS_HOME which point respectively to the directories you have installed the executables of Java and Closure. For example:
JAVA_HOME -> C:\Program Files\Java\
CLOSURE_JS_HOME -> C:\Program Files\Closure\
Note: Make sure to include the trailing slash at the end of each of the two paths.
You can now access the minified javascript that will be generated during the build from C# code, using:
Resources.MyInjectableJavascript_min
Hope this helps. Good luck.
Cheers,
Dominick
When writing javascript for a specific page in a site, when do you want to turn the javascript into a function and include it in application.js?
I've seen suggestions about doing this (and minifying or gzip-ing) to minimize HTTP requests. That makes sense, but what about maintainability? If I have js code specific to one view, it seems like more work to look into a potentially massive application.js. That code could be embedded into that view or put in its own .js (or .js.erb or .rjs) file in that view folder.
I've seen another suggestion that Rails automatically merges all javascript into one file. Is this true?
TLDR: how much or how little should a developer worry about optimization when writing javascript?
As I haven't seen an answer in about a month, I'll answer this question to the best of my current knowledge.
Rails 3.1 (currently at release candidate 4) introduces sprockets, which will compile all javascript in a rails project into one file. It even comes with tools to minify and compress javascript so that it's all delivered to the client at once.
Related to sprockets is the Rails 3.1 asset pipeline. As I understand, it's a folder hierarchy/abstraction. Javascripts can go into 3 folders:
/apps/assets/javscripts/
Javascript files specific to the application, including application.js. This should only contain the manifest of javascript files you want to include in your project. The rails new tool will generate this file and include jquery in the manifest.
/lib/assets/javascripts/
Javascript files written by the developer that are more general purpose. (My impression is that this would be for javascript libraries you develop to drop into multiple applications)
/vendor/assets/javascripts/
Third party javascript files (i.e. JQuery, Modernizr)
All files in these folders will appear to the client inside /assets/, abstracting out the server side file paths. I assume this is meant to help the developer organize javascript files.
To answer my own question
Put javascript functions into separate files, group them logically. My test app indicated that subfolders within .../assets/javascripts/ are ok if and only if the subfolder path is included in the manifest.
I.E. putting //= subfolder/js_file in the manifest will work. Putting //= js_file will not if js_file is inside .../javascripts/subfolder/
DHH mentions a "rule of 13" in his talk (linked below). If the number of javascripts in a folder exceeds 13, it starts to look messy and unmanageable. This would be a good time to group javascript files into subfolders.
Use the built in Rails 3.1 minifier and compressor (or install a preferred gem)
Refactor javascript code from time to time. Move functions to /lib/assets/javascripts/ over time. (The goal is to eventually recognize when you want to write general purpose javascript functions as opposed to application-specific ones and eliminate this refactor step)
More Resources
a blog post covering all changes in Rails 3.1
DHH's talk on Rails 3.1 changes, May 16 2011 (~1 hr)
I work on front end development and am looking to find a solution for working with javaScript between (non compressed and multiple files) development environment and (compressed and combined files) live environment.
I have found a solution with CSS which means that I only need to include one global CSS file with imports, then we combine and compress those imports when deploying to a live environment. This means that we don't have to toggle adding references in to the head for dev and live.
Any ideas on a similar solution for JavaScipt?
Thanks
Dave
If you are using jQuery it's really easy to include external Javascript files from within Javascript which is basically what you described you did with CSS.
Read up on jQuery getScript()
You can use Charles Web debugging proxy. Or smth similar.
Charles allows to give any local file instead of any url. So you can give your browser your local JS file instead of live JS. Thus you will be able to test JS or CSS changes without showing them to your users.
I use ESC to merge and compress all the independant JavaScripts to a central one, and have it run as a 'post build' task.
For Visual Studio I wrote a small console application I wrote (like ESC as someone mentioned) that is used as a post-build event. It's simple but automates the job you're describing by:
Taking a list of filenames as its arguments
Compressing each one using Crockford's JS compressor
Combining the output into one .js file
Then in the site project, the file is loaded from a resource, and a toggle is performed in a class
List<string> files = new List<string>();
#if DEBUG
files.Add("MyNamespace.Javascript.script1.js");
files.Add("MyNamespace.Javascript.script2.js");
#else
files.Add("MyNamespace.Javascript.Live.js"); // single file
#endif
// ScriptManager.Register them
You could also enable GZIP compression on the JS files for even faster load times. If you're not using the Microsoft dev environment then I'll delete this.
Thanks for all your responses. I have come up with a solution which uses some of your ideas.
i have a global js file which has a list of files to include and when run during dev just writes the script links to the page.
Then included in the deployment process is a script which parses the global js file, looks up which files it is linking together, combines and compresses them in to one global js file.
This means that I don't need any server side code during the process which makes things easier to maintain across a team of freelance front end devs.
i'll post the final bunch of code when it's ready on my blog.
I don't know how your dev environment looks like but you could put all the script tags into one file for development and have another for production that has the script tag for your one single file. For example: development_js.extension and production_js.extension.
Then it's just a matter of either using server-side include or some build tool to merge the correct file into your HTML file.