Should JavaScript/jQuery code be in it's own file?

I watched a security tutorial at my previous job and one thing that was mentioned was not to have comments in JavaScript code because would-be hackers might see the comments if they do "inspect" in browser.

I'm working on a new project and I see they have the jQuery code in the page itself. Example below.

Should jQuery code be in its own js file (I think it should) and be minified?

code
LVL 8
CamilliaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chinmay PatelChief Technical NinjaCommented:
Hi Camillia,

It is a good practice to put JavaScript in its own file and minify it while it still does not guarantee 100% protection from attackers it is a one more door for them to break in to.

Regards,
Chinmay.
0
CamilliaAuthor Commented:
How do we minify a js file?
0
leakim971PluritechnicianCommented:
You're supposed to minify/compile your JS code on the production server :
https://closure-compiler.appspot.com/home

Usualy this is done with a tools like gulp or grunt :
https://gulpjs.com
https://gruntjs.com
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

CamilliaAuthor Commented:
Thanks. They have  js code in the html/razor. Not huge js but still it's better to have its own files.
0
Chris StanyonWebDevCommented:
I would suggest it has very little to do with Security and more to do with maintainability and performance.

Having the majority of your JS functions in one (or several) external files would mean you have fewer JS files to maintain, and it's easier to share functions across several pages. You're still going to have some JS in your files (used to call functions from your external file probably / set page specific variables etc.)

An 'attacker' can view your code whether it's in your page or a separate file, so I wouldn't worry about that. Don't use Javascript for anything sensitive ! Comments in code should never be a security risk unless they're used very poorly !!

As has already been pointed out, generally you would minify your JS scripts before they go to production (and maybe combine them) - this is much easier if they are in there own JS-specific files and folders, and can be automated with taks-runners such as Gulp and Grunt. That process should also remove all your comments as well. Streamline the process to include your CSS and you then have your developer friendly source files for testing / debugging as well as the production ready 'compiled' files to send to your server
1
CamilliaAuthor Commented:
Thanks, Chris. Let me read and understand.
0
Chinmay PatelChief Technical NinjaCommented:

Thanks. They have  js code in the html/razor. Not huge js but still it's better to have its own files.

In that case, you can ask them to create separate files and then bundle them. Check out bundling and minification on MSDN: https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification
0
CamilliaAuthor Commented:
I'll take a look. Thanks
0
Julian HansenCommented:
One argument for putting code directly in the page is speed. Each javascript file requires a roundtrip to the server.

One strategy is to put mission critical script in the page and then to load the remaining JavaScript asynchronously from minified, tree shaken files located on a CDN.

In addition to minification, modern JavaScript frameworks use a technique called tree shaking where JavaScript libraries are analysed to see what code is actually used. Unused code is stripped out as part of the shaking process.

So to answer your question - you want to reduce the calls to external resources to a minimum and you don't want to compromise load speed (or perceived load speed).

This means minify your JavaScript and concat into a single file. Load asynchronously where possible and put mission critical code in the document.
2

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CamilliaAuthor Commented:
This means minify your JavaScript and concat into a single file

The non-mission-critical js code can go into one file, correct? and minified

Load asynchronously

How? not sure exactly what this means and how to achieve it?

put mission critical code in the document
This one I understand. The important JS code that are used for processing (there's one in the code to generate a dynamic reports page) is ok to be in the page.

Treeshaking. I found this. It needs to be done on the production server?  https://www.engineyard.com/blog/tree-shaking
0
Julian HansenCommented:
The non-mission-critical js code can go into one file, correct? and minified
Yes
How? not sure exactly what this means and how to achieve it?
Check out $.getScript(url, successCallback)

There is also the async attribute on the <script> tag that will load the scripts async - the page will load and start to "run" while the script loads in the background.

This one I understand. The important JS code that are used for processing (there's one in the code to generate a dynamic reports page) is ok to be in the page.
This would be code that would be need immediately after document load - either initialising the interface or creating UI elements.
1
CamilliaAuthor Commented:
ah, s async here means the page loads, starts to run while the JS code loads.

Is it correct that JS code needs to be at the bottom of a page? for example, we have an aspx page, the top has the html code stuff, the <script> tag for jQuery code is at the bottom...after all the razor/html code.

Some said that to me few yrs ago...that JS code needs to go to the bottom. I think loading/executing the JS code was the reason he gave me.
0
Chinmay PatelChief Technical NinjaCommented:
The JS code can be put anywhere in the code based on where it is being called. In some cases the location matters, for example, if your JS refers to a page element that is present in body and you are not checking if the Page is completely loaded (i.e. all DOM and other necessary components are properly initialized and ready to use) then your script might throw an error.
0
Julian HansenCommented:
s it correct that JS code needs to be at the bottom of a page?
No, there are endless debates out there whether to put it in the head or the bottom. There are arguments for both. In most cases it does not really matter - when you start getting to sites like Facebook then minor optimisations can mean a huge saving.
For instance if you can cut down on 1 server request per Facebook member - what does that mean for your server infrastructure.
For your local mom and pop negligable for the likes of Facebook and Google - those minor savings add up to an impressive amount when you look at the scale of their user base.

My strategy is I look at what the big guys do and then adopt what is practically do-able - in other words I don't spend time and effort on complex implementations that make a negligible difference on the scale I am using. Take what works and feasible add a good dollop of common sense and try to keep a balance between optimisation and manageability.
1
leakim971PluritechnicianCommented:
I will add to add that most of time, your browser cache external file.
You should add a version (or something like that) to each external script, if the version doesn't change, the browser will just use its cache and load the file quickest than download it...

Also, if two sites use the same ressources from a CDN, like this well know plugin (or any one else, same url) :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The browser will not download it, it will use its cache
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.