This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Make File for Javascript
Actually i am writing some javascript for testing purpose.
i want to use multiple javascripts in which functions are defined.
Is there any way to achieve this ?
I think Make file is the way.
But i don't know that also.
I want to generate make file.
Can any body suggest me how is to be done?
Creating makefile is an interesting solution, but you can also use require.js library to set the sequense of loaded scripts.
If you looking to combine multiple scripts as one. You can the use build script Boilerplate.
Why to use it? Its not only about scripts.
Combines and minifies javascript (via yui compressor)
Inlines stylesheets specified using #import in your CSS
Combines and minifies CSS
Optimizes JPGs and PNGs (with jpegtran & optipng)
Removes development only code (any remaining console.log files, profiling, test suite)
Basic to aggressive html minification (via htmlcompressor)
Autogenerates a cache manifest file (and links from the html tag) when you enable a property in the project config file.
Revises the file names of your assets so that you can use heavy caching (1 year expires).
Upgrades the .htaccess to use heavier caching
Updates your HTML to reference these new hyper-optimized CSS + JS files
Updates your HTML to use the minified jQuery instead of the development version
Remove unneeded references from HTML (like a root folder favicon)
Runs your JavaScript through a code quality tool (optional)
If you have several separate files and you want to append them all it into one file before, f.i. using it one your website, then any script or tool is good: Make, Rake, Cake, or your own, in your language of choice. If it goes to the web, it should be also compressed. Now how to do it, is beyond scope of this question, there are loads of articles on the web about all those topics. You are encouraged to come back when (if) you hit some more detailed problem.
Related
I've launched a redesign of our website and I'm using quite a bit of Javascript for the first time.
I've learned that I should be combining all my javascript and css into one file (each obviously) but while I know I can combine the css without problems but the javascript I'm not sure of.
I have to load:
jquery.min.js <-- I load the top two from ajax.googleapis.com, is that a good idea
jquery-ui.min.js
javascript for Facebook
some for google plus button
same for twitter
some for google analytics
then some inline stuff to hide divs which javascript users shouldn't see and that type of thing.
you can see it here: traditionalirishgifts.com
So can I just copy and paste the contents of all these files into one big file. Find some way to minify (haven't looked into that fully yet) it. Load this one file right at the bottom of my page before and bingo?
I'd use this tool: http://jscompress.com/
JSCompress.com is an online javascript compressor that allows you to
compress and minify your javascript files. Compressed javascript files
are ideal for production environments since they typically reduce the
size of the file by 30-90%. Most of the filesize reduction is achieved
by removing comments and extra whitespace characters that are not
needed by web browsers or visitors.
You should always be able to merge all your external JavaScripts into one file. You can use a server-side compressor to cache it and serve it as one file. It does put some constraints on the files, like which file should load first etc. Also, if there is a syntax error anywhere it will crash completely.
Keep in mind that 3rd party code like code from google can't be mixed in. Usually there is some kind of authentication going on (or an API key in the URL). If you try to cache that code, it will stop working after a while. So you do need to keep those separate.
I just finished my website, which I started 2 years ago. I was always trying new things, which sometimes included adding different frameworks or other external JS files.
Now I don't know which of the linked files/lines of JS are unused. Is there a tool which can detect these files and lines of code? It would save me a lot of time.
This answer offers Google's Closure Compiler which, in the process of minifying and concatenating your JavaScript code, can remove "dead code".
Quoting from the documentation for the compilation levels:
Compilation with ADVANCED_OPTIMIZATIONS removes code that is provably unreachable. This is especially useful in combination with large libraries. If you use only a few functions from a large library file, the compiler can remove everything except those functions from its output.
Also see this answer which contains more information on Google's Closure Compiler.
I had this need so I created a tool that detects unused JS on the browser side, not just from the sources, so it can also test third parties scripts.
It works by creating a local proxy on your computer that intercepts JavaScript requests and instruments these files on-the-fly. The tool is than able to detect which parts of the instrumented files have been used by the page, and which don't.
I made it open-source and you can find it here: https://github.com/gmetais/unusedjs.
For this answer, I am not sure whether it's helpful or not. How about trying Sonar. Sonar has a javascript plugin that can check your js code quality and list the code that unused.
I've been looking at a similar task for the past few weeks myself and ended up with the following powershell query:
PS> Get-ChildItem -Path C:\PathToProject\ -Filter *.as?x -Recurse
| select-string -pattern "src=""([^""]*.js)"""
| Select -Expand Matches | Foreach { $_.Groups[1].Value } | select -unique
First it recursively selects all .aspx and .ascx files in our project directory, then finds src attribute values that refer to .js files (presumably those of script elements) and traces distinct values - voila, you have a list of .js files as referenced in your project!
It would be fairly straightforward to adjust the query so that it fits your specific project and its structure. Make sure you don't iterate over outdated files that may include obsolete references. Account for markup discreptancies - could you have used single quotes for attribute values in the past, or left unnecessary whitespace around the "equals" symbol, or both? Could you be including these files programmatically or asynchronously from inside another js files? etc. etc.
In Google Chrome Developer tools, you can now view "Coverage" on the Sources tab to display unused Javascript and CSS by percentage of each file, or even on a line by line basis.
Here's the announcement of the feature in 2017.
Though it is pretty old question, this might help for this type of problem - https://github.com/skpaul/LocateMe
I wrote this to use in my project.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to include js file in another js file?
Suppose I have a few JavaScript source files: a.js, a1.js, and a2.js. Functions of a.js invoke functions from a1.js and a2.js.
Now I have to declare all these files in my HTML page. I would like to declare only a.js in the HTML and "import/include" a1.js, and a2.js in the a.js source file.
Does it make sense? Can I do that in JavaScript?
You can't specify imports in vanilla javascript.
So your solutions (excluding heavy server side frameworks) are :
simply do the imports
concatenate your js files (and minify them in the same move, for exemple using the closure compiler)
use a module itool like require.js
As long as you're not experienced, and if your number of files is low (less than 15), I recommend to simply choose the first or second solution. Using a module loader may have side effects you don't want to debug when beginning to learn javascript.
You can import:
<script type="text/javascript"src="a1.js"></script>
<script type="text/javascript"src="a2.js"></script>
<script type="text/javascript"src="a3.js"></script>
if you want to do it directly from the JS, you may use Ajax, this post explains how to:
include-javascript-file-inside-javascript-file
You can bundle JavaScript (and also CSS) files together using certain tools to reduce the number of files you must include. This also increases page load performance.
These tools combine multiple JavaScript files into a single JavaScript file (optionally minifying the files as well), and multiple CSS files into a single CSS file. This results in fewer HTTP connections from the browser to the server, so there are fewer things to be fetched serially.
ASP.Net MVC 4 has built-in support for this:
http://theshravan.net/bundling-and-minification-support-in-asp-net-mvc-4/
There are a number of solutions for other environments as well such as Juicer.
If you cannot bundle all resources (perhaps some come from a CDN while others are served locally), you can use a load manager such as require.js.
I've been using yuicompressor.jar on my test server for on-the-fly minimisation of changed JavaScript files. Now that I have deployed the website to the public server, I noticed that the server's policies forbid the use of exec() or its equivalents, so no more java execution for me.
Is there a decent on-the-fly JS compressor implemented in PHP? The only thing resembling this that I was able to find was Minify, but it's more of a full-blown compression solution with cache and everything. I want to keep the files separate and have the minimised files follow my own naming conventions, so Minify is a bit too complex for this purpose.
The tool, like yuicompressor, should be able to take either a filename or JavaScript as input and should either write to a file or output the compressed JavaScript.
EDIT: To clarify, I'm looking for something that does not have to be used as a standalone (i.e. it can be called from a function, rather than sniffing my GET variables). If I just wanted a compressor, Minify would obviously be a good choice.
EDIT2: A lot has changed in the five years since I asked this question. Today I would strongly recommend separating the front-end workflow from the server code. There are plenty of good tools for JS development around and except for the most trivial jQuery enhancements it's a better idea to have a full workflow with automated bundling, testing and linting in place and just deploy the minified bundles rather than the raw files.
Yes there is, it's called minify.
The only thing in to worry about in the way of complexity is setting up a group, and there's really nothing to it. Edit the groupsConfig.php file if you want multiple JS/CSS in one <script> or <link> statement:
return array(
'js-common' => array('//js/jquery/jquery-1.3.2.min.js', '//js/common.js', '//js/visuals.js',
'//js/jquery/facebox.js'),
'css-common' => array('//css/main.css', '//css/layout.css','//css/facebox.css')
);
To include the above 'js-common' group, do this:
<script type="text/javascript" src="/min/g=js-common"></script>
(i know i was looking for the exact same thing not knowing how to deal directly with the jar file using php - that's how i ended up here so i'm sharing what i found)
Minify is a huge library with tons of functionalities. However the minifying part is a very tiny class : http://code.google.com/p/minify/source/browse/trunk/min/lib/Minify/YUICompressor.php
& very very easy to use :
//set the path to the jar file
Minify_YUIcompressor::$jarFile=_ROOT.'libs/java/yuicompressor.jar';
//set the path to a writable temp folder
Minify_YUIcompressor::$tempDir=_ROOT.'temp/';
//minify
$yourcssminified=Minify_YUIcompressor::minifyCss($yourcssstringnotminified,$youroptions)
same process for js, if you need more functionalities just pick from the library & read the source to see how you can make direct call from your app.
I didn't read the question well, since minify is based on using the jar files, the op can't use it anyway with his server config
Minify also include other minifying methods than yui, for example:
http://code.google.com/p/minify/source/browse/trunk/min/lib/JSMinPlus.php?r=443&spec=svn468
Try Lissa:
Lissa is a generic CSS and JavaScript loading utility. Lissa is an extension of the YUI PHP Loader aimed at solving one of the current loader limitations; combo loading. YUI PHP Loader ships with a combo loader that is capable of reducing HTTP requests and increasing performance by outputting all the YUI JavaScript and/or CSS requirements as a single request per resource type. Meaning even if you needed 8 YUI components which ultimately boil down to say 13 files you would still only make 2 HTTP requests; one for the CSS and another for the JavaScript. That's great, but what about custom non-YUI resources. YUI PHP Loader will load them, but it loads them as separate includes and thus they miss out on benefits of the combo service and the number of HTTP requests for the page increases. Lissa works around this limitation by using the YUI PHP Loader to handle the loading and sort of YUI and/or custom resource dependencies and pairs that functional with Minify.
This question already has answers here:
Closed 14 years ago.
Duplicate of: Use javascript to inject script references as needed?
Javascript doesn't have any directive to "include" or "import" another js file.
This means that if script1.js uses functions/objects defined in script2.js, then every html page that includes script1.js must include script2.js before it.
This shouldn't be a big problem if you only have 2 js files in like 10 html pages. I mean, it's manageable then!
But say suddenly you change script1.js and improve it by using functions/objects defined in a new file, script3.js
The problem is, you can't just tell script1.js to include script3.js, instead, you have to remember every html file that included script1.js and update it to include script3.js as well!
This seems like rather stupid way of organizing code.
Are there recommended strategies or practices to deal with this issue?
Would it be acceptable to have a gigantic js file that holds all the functionality that you use across the website?
Use dynamic includes:
Use javascript to inject script references as needed?
Scriptaculous (and probably other frameworks) handle this by writing script tags for the included files to the document when they are loaded. Below is the relevant bit from the scriptaculous.js file that allows loading the other files in the framework.
var Scriptaculous = {
Version: '1.8.2',
require: function(libraryName) {
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
},
...
Personally I try to avoid all this confusion by rolling all my javascript into one file. If there's one page which requires a LOT of javascript which the other pages don't need, then just have two files - generally the page-specific JS can be loaded after the generic js without hassles anyway.
To roll the JS files into one, I use Dean Edwards's Javascript Packer, combined with a helper script that I described on my blog. It makes working with many JS files muuuuuch easier (for me at least), and the compression you get from packing the javascript is better.
I guess you could use document.write in your JS files to make sure they include whatever dependencies they're dependent upon, though I wouldn't really recommend it...