I want to log to the console when I'm using un-minimized JavaScript files.
Comments are taken out already when I minimize JavaScript. I'm wondering if there's a way I can write a command that isn't commented out but will still be taken out when I minimize the JavaScript file.
I think I'd be pretty upset if a Javascript minimizer changed the behaviour of my code based on some funny/clever/odd code construct. How could you ever be sure that code construct isn't there intentionally?
As has been suggested, have a variable that disables logging. Then as part of your minimize script or batch job, you can swap that variable to its non-logging state using sed (for example) before minimizing.
If your goal is just to reduce the js size you can separate you logging functions into a separate file.
In your "main" js add a function function doLogging(object){} then in your separate logging functions file replace the function with function doLogging(object){/*your logging code*/};
Just remember to include your main js before the logging js. When you minify just comment out the logging script tags from the html. This way you will only have one (or a couple of) empty function definitions in the minified js and one line of code calling those functions per loggingn action.
Unless whatever you're using to minimize your JS supports conditional statements I don't think you can do this.
Why not just log things if a certain variable is set?
Related
I have seen a lot of websites with some function (p,a,c,k,e,d) in their JavaScript code. The different websites may have different bodies of this function, but they all use the same parameter names (p,a,c,k,e,d). Is it a standard or a library or something?
Secondly, it seems that this function is supposed to be executed as soon as the page loads. Like the following snippet from a website.
Can you help me in understanding this code? eval() is used to evaluate expressions like 2+3 but how is the following code passing a function to it?
try{
eval(
function(p,a,c,k,e,d)
{
//some code goes here
}
}catch(err){}
So if you use http://matthewfl.com/unPacker.html as I posted in the comments, it "unpacks" the code into this:
(function()
{
var b="some sample packed code";
function something(a)
{
alert(a)
}
something(b)
}
)();
It doesn't seem to be malicious. For a soft argument on why you would use this, see javascript packer versus minifier:
Packed is smaller but is slower.
And even harder to debug.
Most of the well known frameworks and plugins are only minified.
Packer does more then just rename vars and arguments, it actually maps
the source code using Base62 which then must be rebuilt on the client
side via eval() in order to be usable.
Side stepping the eval() is evil issues here, this can also create a
large amount of overhead on the client during page load when you start
packing larger JS libraries, like jQuery. This why only doing minify
on your production JS is recommend, since if you have enough code to
need to do packing or minify, you have enough code to make eval()
choke the client during page load.
Minifier only removes unnecessary things like white space characters
where as a Packer goes one step further and does whatever it can do to
minimize the size of javascript. For example it renames variables to
smaller names.
It's a function which decompresses compressed/obfuscated javascript code. Many JS libraries and scripts make use of it.
There are online tools where you can pack and unpack code via the browser, which use the function.
As I have seen that eval(function(p,a,c,k,e,d){}) is used in http://www.indiabix.com which uses it for hiding whole contents when user get download the page and open it . Maybe that is the inner workings of the particular code.
Our web project has a very big js file which actually is an aggregation of modified legacy 3rd party libraries.
Only about 5-10% of code from this file is used in the application. So as an attempt to optimize js size I made a folllowing plan:
Make a js function call logger (like it was done here)
Run all cases of the application
Check which methods where called and mark their lines of code (coverage).
In order to do (3) I need to know which lines of code where included in called method. Then I could use it to format JS out as html and highlight used code. But question is how to know what are this lines?
I can exploit console.trace method but it is giving only entry line, not exit line (and even it do, that would be pointless, because exit line is not always end of method). So it looks like I need to get code properties (like code start and code end) of certain function.
How to get start and end line of certain JS function?
Update: I've found a lib which can do almost same thing (istanbul.js), but still welcome answers to the question above.
I have a log.js file(it contains log function along with some properties) for debugging purpose.
I have two other js file which are the controlling various behavior of the web application.
Now I need to include the log function considering not to repeat the debug function in both the js file and just calling the file name.
How do I do it?
The idea is to make my code clean and separate them in other files to limit the size of a single js file.
Include all .js-files in the html page. Include log.js first.
Call the functions all you want.
All functions in all files are included in the source and are "written on the page", any functions can be accessed from anywhere within the HTML as they all become essentially one document. Make sure you do not have duplicate functions as this could cause an issue
In todays modern age, where lots of (popular) javascripts files are loaded externally and locally, does the order in which the javascripts files are called matter especially when all local files are all combined (minified) into one file?
Furthermore, many claim that Javascript should go in the bottom of the page while others say javascript is best left in the head. Which should one do when? Thanks!
google cdn latest jquery js | external
another cdn loaded javascript js | external
TabScript ...js \
GalleryLightbox ...js \
JavascriptMenu ...js \
HTMlFormsBeautifier ...js > all minified and combined into one .js file!
TextFieldResize ...js /
SWFObjects ...js /
Tooltips ...js /
CallFunctions ...js /
Order matters in possibly one or more of the following situations:
When one of your scripts contains dependencies on another script.
If the script is in the BODY and not the HEAD.. UPDATE: HEAD vs BODY doesn't seem to make a difference. Order matters. Period.
When you are running code in the global namespace that requires a dependency on another script.
The best way to avoid these problems is to make sure that code in the global namespace is inside of a $(document).ready() wrapper. Code in the global namespace must be loaded in the order such that executed code must first be defined.
Checking the JavaScript error console in Firebug or Chrome Debugger can possibly tell you what is breaking in the script and let you know what needs to be modified for your new setup.
Order generally doesn't matter if functions are invoked based on events, such as pageload, clicks, nodes inserted or removed, etc. But if function calls are made outside of the events in the global namespace, that is when problems will arise. Consider this code:
JS file: mySourceContainingEvilFunctionDef.js
function evilGlobalFunctionCall() {
alert("I will cause problems because the HTML page is trying to call " +
"me before it knows I exist... It doesn't know I exist, sniff :( ");
}
HTML:
<script>
evilGlobalFunctionCall(); // JS Error - syntax error
</script>
<!-- Takes time to load -->
<script type="text/javascript" src="mySourceContainingEvilFunctionDef.js"></script>
...
In any case, the above tips will help prevent these types of issues.
As a side note, you may want to consider that there are certain speed advantages to utilizing the asynchronous nature of the browser to pull down resources. Web browsers can have up to 4 asynchronous connections open at a time, meaning that it's quite possible that your one massive script might take longer to load than that same script split up into chunks! There is also Yahoo Research that shows combining scripts produces the faster result, so results vary from one situation to another.
Since it's a balance between the time taken to open and close several HTTP connections vs the time lost in limiting yourself to a single connection instead of multiple asynchronous connections, you may need to do some testing on your end to verify what works best in your situation. It may be that the time taken to open all of the connections is offset by the fact that the browser can download all the scripts asynchronously and exceed the delays in opening/closing connections.
With that said, in most cases, combining the script will likely result in the fastest speed gains and is considered a best practice.
Yes, depending very much on what you do.
For example, if a.js had...
var a = function() {
alert('a');
}
...and b.js had...
a()
...then you wouldn't want to include b.js before a.js, or a() won't be available.
This only applies to function expressions; declarations are hoisted to the top of their scope.
As for whether you should combine jQuery, I reckon it would be better to use the Google hosted copy - adding it to your combined file will make it larger when there is a great chance the file is already cached for the client.
Read this post from the webkit team for some valuable information about how browsers load and execute script files.
Normally when the parser encounters an
external script, parsing is paused, a
request is issued to download the
script, and parsing is resumed only
after the script has fully downloaded
and executed.
So normally (without those async or defer attributes), scripts get excuted in the order in which they are specified in the source code. But if the script tags are in the <head>, the browser will first wait for all scripts to load before it starts executing anything.
This means that it makes no difference if the script is splitted into multiple files or not.
If I'm understanding your question I think you're asking if it matters where in a file a function/method is defined, and the answer is no, you can define them anywhere in a single source file. The JavaScript parser will read in all symbols before trying to run the code.
If you have two files that define variables or functions with the same name, the order that they're included will change which one actually is defined
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
How do you guys organise your javascript code? I know that it is good practice to store the code in an external .js file and this is fine for code that is run in multiple pages but how do you organise if you have, say 20 pages, and only 1 of them uses a particular function. Do you create a new external file for that 1 page or create the code inline?
I do two things:
I put all my site's Javascript in one or more files;
I include that file or files on every page that uses any Javascript;
Those files are cached effectively such that they are only ever downloaded once (until they change); and
Pages call the functions they need from those external files.
If your site is one page then put it inline.
If your site is 20 pages and they all use a little bit of Javascript, put it all in one files, include it on every page and call the functions with inlien Javascript as necessary in each file.
I write about this and more in Supercharging Javascript in PHP. Sure it's PHP-specific but the principles are universal.
Basically every extra HTTP request is a problem. So if you have 20 pages each with a different Javascript file then that's a problem, even if those files are small. It's better to combine all that Javascript in one file, download it just once (with effective caching) and just use what you need.
To give you an example. External JS file contains:
function delete_user(evt) { ...}
function suspend_user(evt) { ... }
function unsuspend_user(evt) { ... }
One of your Web pages contains:
$(function() {
$("#delete").click(delete_user);
$("#suspend").click(suspend_user);
$("#unsuspend").click(unsuspend_user);
});
This way you get an external JS that contains all your site's Javascript but none of it is actually used. Use comes from inline code in the pages. This way there is no overhead of having the larger JS file.
Whatever you do, don't put in ALL initialization in your Javascript file. I once made this mistake and put a huge $(function() { ... } function into the external file on the grounds that if the relevant IDs weren't in the page, nothing would happen. There ended up being enough of this code to add nearly half a second to the page load time (and the site wasn't that big).
The browser shouldn't redownload the javascript file once it has it, so I would put it into the single Javascript file. That saves another connection/request to the webserver, and it keeps the code in one place rather than having script tags and code in your HTML/JSP/PHP/etc files. I.e., it's more maintainable, and it's very little overhead to get the code (unless it's a 1000 line monster! but that's another problem entirely) even if it isn't used.
Not that I don't have script blocks in some files, for very very specialised cases. In the end it comes down to what you are happy with - but consistency across the project is what is most important, so don't have a one off script in one place, and then do something different elsewhere.
ALWAYS put JavaScript in a file external to HTML. The problem with JavaScript that exists in page is that it typically exists in the global namespace, which could easily cause namespace collisions that makes code crash.
So, always put JavaScript in an external file.
With that said you should organize your code in an object-oriented manner. Try to capture an entire application representing a single point of execution to a single named function. Always write your code using a single var command per function, which should go at the top of the function, so that your code is easier to read. Ensure all variables and functions are declared with a var command or they will into the global namespace, which is potential failure. Put sections of execution of a giant function into smaller child functions, because this makes code easier to maintain when you can point to a particular named block when debugging or writing enhancements.
Also, always run your code through JSLint to verify syntax accuracy.
If you only have a small amount of code I don't believe it is worth the effort to split it up.
Depending on how much JS you have, consider a build process that can concatenate your separate JavaScript files into one, minified single download.
YUI is incredibly modular. They have a 'core' set of includes and then you can supplement these with the widgets you actually use. For instance, I have no interest in using their file uploader widget so never include the JS for it.
Cache the JS for a date far in the future. If you need to make a change, append a version stamp to the end of the SRC attribute, i.e. my-code.js?v=91
Use namespaces to avoid polluting the global scope. Again, YUI is very organised in this regard - see the YAHOO.namespace() function.
I would say put it in an external file. Chances are you will need to add new functions to it anyway, but also, from an SEO point of view, keeping it in an external file is preferable.
For only one function it would be better to code inline.
I won't include a 100KB Util script file for just calling a Trim function inside it.
If the file is already cached then it won't be a problem if you refer this in a page which calls only one function inside the file.
If I have a choice, I put the JS functions in external files, but not all in one file. Cache or no cache, I group files by their functionality and organize them similar to Java packages. If I have an utility function, say something generic like trim(), that goes to the top most JS file and all pages can use it. If I have something specific to a part of the site (unused in other parts) that goes in something like a sub-package, just for that specific part… and so on.
Of course you must use common sense so you don’t overdo it, and have let’s say a function per JS file. If you have fine grained JS files, that will affect you when your site evolves and you find yourself moving functions from sub-packages to an upper package or the other way around. I think one parent utility JS and one JS per site functionality should, most of the times, suffice.