Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we hide javascript comment in page when it renders ?

question may seems to be silly, just i am curious about this. suppose in my html or aspx page i added comment for some javascript code, when the page loads, it renders as the page it is inlcuding comments. as i thought that comment will be ignored from the execution. is it same apply for rendering ? will it be possible.

  1. Comment are used to describe what the code does. so below i wrote " this for replacing image ". can we hide from rendering.

P.S : As this question has no special reason, just i am curious . whether it is possible or not.

$(".SomeID").slice(5, ExpandLength).each(function() {
                this.src = this.src.replace("some.gif", "som1.gif"); // this for replacing image 
            });
like image 556
Ravi Gadag Avatar asked Mar 15 '12 13:03

Ravi Gadag


2 Answers

Look at YUI to minimise your javascript. You will need to do some post-processing using a tool like that when you deploy to remove comments. Otherwise, you're just sticking the same file up and people can see what you do (just like html or anything else that is served to the user directly).

Look at this question for a good answer:

YUI remove javascript comments

PS I'm assuming your javascript is in a .js or a .html file, otherwise (if in an asp, aspx or php file) the other answers about using server side comments are the best way to do it.

Still.. your javascript should be in a js file. It's much easier to manage :)

like image 157
Gats Avatar answered Oct 12 '22 23:10

Gats


Rendering is a term that is applied to two distinct stages of the process.

  1. When the ASP generates some output to send in the HTTP response
  2. When the browser parses the HTML and creates a visible representation for the user

A comment in JavaScript is, as far as the ASP is concerned, just another piece of text. It sees no difference between that and a piece of HTML or any other part of the JavaScript. Therefore, during stage 1, it will be passed through to the browser.

When the browser receives the response it processes the HTML and JavaScript and generates the webpage for the user to see. When it is executing the JavaScript the comment has special significance (i.e. it should be ignored) so it isn't executed.

It is still part of the source code though.

To prevent that you would have to run the JavaScript through a JavaScript parser on the server, remove the comments, then output whatever remained.

It is a common practise to keep JavaScript in external files and to process them using a minifier (a tool that removes unneeded text from the JS, such as comments and white space) before deploying the site to the server.

like image 27
Quentin Avatar answered Oct 12 '22 21:10

Quentin