rewriting Javascript before it's loaded by the browser - javascript

I need to arbitrarily rewrite Javascript code, client-side, before it's loaded by the browser. I would like to handle script tags as well as referenced .js files. Dynamically generated script tags are not a goal. My client is running a proprietary system, so this only needs to work with IE for now (IE6+). I've read up on MIME-filtering, but I don't think that would take care of static script tags, just .js files.

What is the use case for this? It sounds like an approach to be avoided if at all possible. You will lose any ability to cache javascript for one thing.
Can you give an example of the kinds of rewriting you want to do?

Ouch, nasty. Would it be possible to configure users' browser with a custom proxy which can parse and rewrite the javascript? This could be pushed out with group policy (if the browsers are not already configured with proxies)

Related

Why do these files have random strings for filenames?

I've come across sites with CSS and JS filenames like this:
css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css
What's causing this or why would you do it?
Edit: Some of each answer below could apply to this scenario, but given the sites I've found this on, serving/caching methods seems the most accurate.
Versioning and making sure that correct version of static resources is being served.
If you have a high traffic website and you serve lots of users you will have several layers of caching: CDN, caching headers on files, etc.
Sometimes it can be hard invalidating the caches with the same filename. Server might pass the correct headers, but client might disregard them and still load cached version. Serving different file name prevents that and ensures that you have correct version of css/js and other static resources.
As you can probably tell, no human came up with that name.
Typically it's
the result of combining multiple CSS files into a single file. This is
done for performance reasons (requesting one file is faster than requesting two.)
The name is likely to be the result of a deterministic algorithm on the
input (i.e. a hash), such that if you perform the combination again but haven't changed the CSS, the output will be given the same name.
When the content (CSS) changes, the name of the output file will change.
This is useful because it makes it impossible for a browser to cache
the old version.
It looks like the file was generated, server-side, for minification.
The website you're visiting might have had multiple CSS files (perhaps combined with #import statements) and JS files (jQuery, jQuery UI, jQuery plugins, some custom code, etc) - rather than have the developer manually minify and combine the files the server might do it for them (ASP.NET 4.5 does this, for example). In this case it uses an arbitrary (random? GUID-based?) filename to ensure it doesn't conflict with anything.
It may be the technology used by the website.
i.e. if you use gwt (it's some java compiled in javscript) or something else that preprocess some code and outputs javascript, you will likely to get weird filenames.

Is it beneficial to inline all JavaScript when deploying a website

In our HTML page, we have a list of tags to load in many (small) JavaScript source files.
For deployment we plan to concatenate the individual JavaScript files into one bundle which will be included in the HTML page, to save on 'expensive' HTTP requests.
But would it be even more beneficial, to just write all the JavaScript directly into the HTML file, in an in-line Javascript tag?
If the JavaScript code changes on every request ("tags"?), then yes, it's beneficial.
Otherwise: No, because the browser will not be able to cache the JS files.
the best way would be to concatenate them but don't put them directly into you html-file. that way the js-file can be cached independently from the (probably) changing html-source.
A file is better than writing the whole stuff into the HTML, as you can cache the javascript file coming from your server, but unless you cache all .html files, you won't get this benefit (i.e. browsers have to keep redownloading all the inline scripts inside your html files)
But would it be even more beneficial, to just write all the JavaScript directly into the HTML file, in an in-line Javascript tag?
No! You would increase the size of every request and destroy cacheability. One big (but external) JS file is the way to go.
Make sure the JS file is emitting the proper caching headers, and it will be loaded only once per client. Unless your JS is exceedingly small (and your description doesn't sound so), that's pretty much the optimum.
I'd suggest that you compile all your javascript into one file and load it with one <script> tag. Yes, HTTP requests take some time, and browsers limit number of concurrent requests (to one domain).
I wouldn't put all javascript in the HTML, because this is mixing logic and representation, prevents caching (of javascript), etc. Avoid this.
This is the general rule I follow: separate content that changes often from content that changes rarely. This way static content will be cached efficiently. And you can optimize "fluid" content (gzip, minify, etc.) so that it takes less time to load.
I'm assuming that you mean 'embed inside a <script> block' rather than in 'on*' attributes inside the HTML elements. If that's not the case, the answer is a definite no - 'on*' attributes are harder to maintain, and typically bad for accessibility.
Normally the answer is no, because although the user's first request will be more expensive if it has to get external resources, those resources will be cached so future requests will be cheaper. If you embed everything, the user has to load them every time they load the page.
So it depends on a few things, the most important of which are probably:
Are users browsing multiple pages? Will they return? If the answer to both questions is 'no', then there is no benefit from caching, so embedded JavaScript can be quicker.
Is the JavaScript static? If it's dynamic - as in, changes on every page load, then again, caching is irrelevant. You could probably improve your JavaScript architecture to separate the static bits from the dynamic.
You can mix the JavaScript so that static JavaScript is linked, while dynamic or page-specific JavaScript is embedded. This is especially useful with libraries - it may already be cached in the client from another site, but if not, you're still loading from a CDN like Google, so it's very quick.
I wouldn't have thought so.
I always just include files and try to keep my base html looking as clean as possible.
Die hards will say don't do it, separate content from styles and scripting, and I agree. But if its not a lot of JS, you may as well save on any additional HTTP requests. Yes, the browser won't cache it, but that's because it won't need to. And on an SEO basis, Page ranking is improved with faster page load, determined possibly on first visit, not after a cache.

Only running javascript required for current page, best methods?

So I know it's best to have one javascript file for an entire site to limit http requests. So obviously only some javascript is required for some pages. What is the best way of only running the javascript required for the current page?
EG.
if(page=='home'){
//run javascript require for the home page
}
Maybe this isn't an issue and if targeting elements are not found on the page javascript will just fail gracefully? I would just like to know the best practice for this javascript structure.
Encapsulate your logic in functions. Then just call the function(s) you need in each page, either via "onload" or an embedded function call in the page:
<script type="text/javascript">
yourFunctionForThisPage();
</script>
Edit: Just to clarify: my answer is assuming the (implied) constraint of a single .js file. As others have pointed out, although you save on HTTP requests, this is not necessarily a good idea: the browser still has to parse all the code in the file for each page, whether used or not. To be honest it's pretty unusual to have a global site-wide js resource with everything in it. It's probably a much better idea to logically split out your js into various files, i.e libraries. These libraries could be page-based - i.e specific code for a particular page, or algorithm/task-based that you can include in whatever pages need them.
Is this feasible?
While it is best to have just a single Javascript file per page to lower the number of requests yet it may not be feasible. Especially the way that you'd like to do it.
If you're asking how to join various scripts of various pages into a single script and then running just those parts that are related to a particular page then this is something you shouldn't do. What good is it for you to have one huge file with lots of scripts (also think of maintainability) compared to a few short integrated scripts? If you keep the number of scripts low (ie. below 10) you shouldn't be to worried.
The big downside is also that browser will load the complete script file which means it will take it more time to parse them as well as consume a lot more resources to use it. I'd strongly suggest against this technique of yours even though it may look interesting...
Other possibilities
The thing is that the number of Javascript files per page is low. Depending on the server side technology you're using there are tools that can combine multiple script files into one so every page will just request a single script file which will combine all those scripts that this particular page will use. There is a bit overhead on the server to accomplish this task, but there will be just one script request.
What do you gain?
every page only has scripts that it needs
individual script files are smaller hence easier to maintain
script size per request is small
browser parsing and resource consumption is kept low
Know what you will need on the page and use a script loader like labjs.
Also, remember that your specific case might be different from what others have found, so you might want to do some tests, to verify if, for example, having 5 little files, is better (or worse) than 1 big file.
The only way to be sure is to test different options yourself and come up with a fitting solution.

why use external javascript?

What are pros of using an external javascript file? I just can't figure it out, I see big websites using them all around several times instead of server-side includes. Is it just for caching?
If it's a matter of clean code and seperation of concerns, then you can still include it from the serverside into the html. For example I use SMARTY and I can just include the file {include file='javascript.js} inside <script></script> tages.
If it's for performance I can't see anything other than an extra http request that makes the external file slower involved. I'm sure I must be missing something because all the big websites still do this.
Is it because of caching the file? my javascripts are dynamic and shouldn't be cached anyway.
could someone help me out to make the right decision to choose what to do with my javascript files.
ps:can a 1.5K user create a tag for external-javascript?
The most important is that the file is cached by the browser. The fewer bytes that need to be sent from the server the better. This is a big part of web performance.
Second to that, it provides modularity.
I'm not sure why your JavaScript is dynamic, but I suggest you rewrite it in a way that removes that need. That in itself might be an issue for you down the road.
In your case where there is no caching because the entire javascript file is generated dynamically, inline is probably superior. It saves you the HTTP overhead.
Source: http://developer.yahoo.com/performance/rules.html#external
they also help the developers separate different conceptual areas of their code. It can get real annoying looking at hundred to thousands of lines of js in a single file, on top of complicated html.
Besides what #Gabriel said, it also helps you use the same function in different pages, withouth the need for them (.html docs) to be larger.

Can we use any type of javascript code as a external .js file or sometime it's necessary to place in <head>?

Can we use any type of javascript code as a external .js file or sometime it's necessary to place in <head>?
The only time you would ever need to inline a js function in your HTML using the <SCRIPT> tags is if your javascript is generated by your server side program depending on the data, user settings etc.
Even this case is extemely rare as as you should be able to create a .js function whose behaviour is controlled by passing parameters.
Apart from keeping everything tidy and in the place where you expect to find it, there is a network performance advantage in that *.js files are cached on the client side so you are not constantly sending the same stuff over the network again and again.
Unless it is a Dynamic content which is placed by the server side scripts (very rarely used as there are many more better alternative methods) .. You can use JS in an external file ..
External js is re-usable .. I mean can be used by more than one HTML page .. So obviously it brings down the burden on browser ..
The site providing the live telecast or the NEWS/information (example:cricket scores etc) real-time examples for Dynamic content ..
You can place it all in an external file. It's much cleaner, and easier to maintain. It's a good practice to keep Javascript and CSS in their own external files. Do away with inline switching between CSS, HTML and Javascript for a much better organized project and less frustration down the road.
if using jquery then $.document.ready() is the way to go

Categories

Resources