Keeping my jQuery code away from the html files - javascript

I am learning jQuery and have a created several plug ins.
Unfortunately due to my company's coding practices they want all javascript code to be extract out to js files. This for me poses two challenges:
Can i extract the actual $(document).ready(..) call to a js file? So far with my limited knowledge I have not figured if this at all possible. If not, I welcome any suggestions to make this cleaner and more acceptable way to include this code.
There are too many javascript includes for each asp.net page header since I may be using several plugins. Is there a way to reduce the potential costly server trips that I would need to make each time I need these files?
Any suggestions, corrections are greatly appreciated
thanks

1. Absolutely.
Just add a script reference to your html like this:
<script type='text/javascript' src='js/yourfile.js'></script>
Then just start your .js file with
jQuery(function() {
foo;
...
bar;
});
or any other shortcut ways of starting the jQuery code block.
2. You should run your scripts through something like Minify before sending them off to the user. This will combine the files and pack them in nicely, so that they take up less space.

Using $(document).ready () in an external javascript file is fine - it will work exactly the same :) In fact - not only will it work, but it is good practice as it helps to seperate the content (HTML) from the behaviour (Javascript).
In response to your section question - you can combine all of your plugins into a single javascript file and link to that one inside the <head>. You could also try minifying the scripts, although this is normally a bit overkill until the site goes live.
When I use jQuery, I normally use this kind of structure:
<html>
<head>
<!-- html tags such as title, link, meta etc -->
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript" src="/path/to/plugin.js"></script>
<!-- more plugins included if required -->
</head>
<body>
<!-- html here -->
<!-- script is the last thing before the ending body tag (increases performance) -->
<script type="text/javascript" src="/path/to/your_jQuery_code.js"></script>
</body>
</html>

I think worrying about server trips for javascript includes is premature optimization. Do you have any evidence that these pages are loading slowly? The browser should be caching the javascript files.
If you do have evidence that this is a problem, you could
-combine the jquery code and any plugins into one file
-write an .net content handler to do this for you (probably overkill)
Then you can add a custom js file per page to handle page specific properties.

You can most definitely put your document.ready and all other JavaScript code in an external file.
Typically I have 2 calls - one for jQuery itself, and one minified global.js file that combines and minifies all of my individual files.
Personally, I like to use front end blender for this, but there are many other options available as well.

there's nothing wrong w/putting the document.ready call in an external file. in fact, it's what i do to separate my js from my html. if you're concerned about certain functions running on certain pages, you may sift through them with a
var path = window.location.pathname;
if (path == "/yourdir/yourpage.html") {
//do something for this page only
}
or you can just include certain files only on certain pages.

Related

Is it okay to have 1 .js file for each html page?

Can I write it like this? Won't I have issues in terms of how fast my website loads?
for index.html:
<html>
<body>
<script src="index.js"></script>
</body>
</html>
for about.html:
<html>
<body>
<script src="about.js"></script>
</body>
</html>
for contact.html:
<html>
<body>
<script src="contact.js"></script>
</body>
</html>
I just want to clear things up. Thanks in advance!
You should extract out common features among all the javascript code you run on different pages.
Imagine index.js has a function to create a list. And about.js has the same function. When it comes to updating that function you will want to change it in one place. Not the five pages you have.
As for speed if every page has a link for list.js file, it will only need to be downloaded by the browser once. It's code will be cached and used in all the other pages requested.
Yes you can use it like this way, your website load faster. But if you include all the JS to all the files, it'll load slower because loading time is increased coz all the three files load for all the three pages.
Or a different approach.
Try to convert all the three file into only 1 (This way you'll reduce the repetitive function)
Then include this file to each file.
By storing the file to cache memory, file only download (load) once then it'll be used from the cache memory. This way your speed will be increased.
Refer to the following link:
https://www.html5rocks.com/en/tutorials/appcache/beginner/
Try to research as much as possible. You'll get your solutions.
Tick right (✓) if my answer is helpful for you.
The pages load separately so having a script in another page does not affect how fast the current one loads.
In my opinion, if you are very concerned about the speed it is more important to ensure that you are only loading the scripts that you need in the current page.
The right approach is to split your code into multiple functions as appropriate.
To address loading performance, use a minifier which will minify and bundle all your code (include JavaScript, CSS and HTML). You won't be able to outperform an actual minifier anyway.
Depending on the technology you are using, minification can be a step during your build/deployment procedure, or a plugin for your CMS which will minify and cache your files as they are being accessed.

Meteor : add elements to the app.html

The sourcecode of the app.html in a meteor app will look like this :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/846a8d9499cc559cd36226c07803f069a9b314a4.css">
<script type="text/javascript" src="/bd418141a43a911de5fcb0fc9eef1599abd72874.js"></script>
<title>application title</title>
</head>
<body>
</body>
</html>
This is simple and nice. (you can add meta in the head part).
But what if I want to add a loader for the app ?
I use a few libraries and my main js is probably going to weight a little more than one mo. I cannot image display nothing while it's loading.
The easier way would be to write a few line of classic inline html. But when I write something in the html, it's inclueded in my templates.
How would you change the app.html ?
Short answer: You can't. As far as I'm aware, Meteor will always send down an empty <body> tag and fill it in via templates.
If you have so much code that the concatenated JavaScript is quite heavy, you can split parts of it off. See this question for some techniques on how to do so. Personally I try to load from CDN any libraries that I'm using "out of the box," like Bootstrap (not an option for jQuery, unfortunately). To load from CDN, just include a <head> block in one of your HTML files and link to the CDN-hosted library files like normal, and leave them out of your project. Another option is to use jQuery's $.getScript() to load specific scripts on demand only on the pages that need them.
But that just lessons the load of your concatenated JavaScript file, it still doesn't really answer your question of having some HTML sent to the client immediately. To accomplish that, the only method I'm aware of is to have some other Web server in front of Meteor. For example have an Apache or Nginx server listening on port 80 that sends down a simple HTML file that has your initial content, and also loads the two Meteor-generated concatenated .js and .css files. Meteor would either replace the contents of <body> on load, or you would need to write some JavaScript to do so so that it gets "handed off" to Meteor so that Meteor can start rendering its templates there. I doubt the handoff would be very smooth, unfortunately. Alternatively if your initial page is more of a splash page, for example a simple login form, it could exist by itself served by Apache/Nginx and then on submit the user moves into the Meteor-served world. While the user is filling in the form the concatenated .css file (if not both the .css and .js files, or the .css file and any CDN-served or non-concatenated .js files) could be downloading in the background and getting cached. To be honest though I'm not sure it's worth all this effort, it adds a lot of complexity for what's probably only a very slight speed improvement (and even then, only on the initial load of the home page).

javascript segregation/performance in an ASP.NET MVC Application

We have an MVC 4 web application with a number of areas.
There is a main layout view that is used by all the pages on the site and it contains all of the CSS includes, the render body tag, then all the JavaScript libraries.
<head>
<link rel="stylesheet" media="screen" href="~/Content/jquery-ui-1.10.3.custom.min.css" />
..
</head
<body>
<div id="main-content">#RenderBody()</div>
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.min.js"></script>
..
</body>
The JavaScript consists of common libraries such as jquery, jqueryui and plug-ins.
There is also a single JavaScript file that contains the custom code for the whole site
Since there is only 1 large JavaScript file with thousands of lines, code routines are initialized by checking for the existence of a particular DOM element to decide if it proceeds.
runExample = function() {
if ($(".Example").length > 0){
// execute code
}
}
..
runExample();
This is of course problematic since there is a great deal of script included for all files, while there is code that applies to all pages, most of the code only applies to certain areas or pages.
Is there a better way to split the JavaScript up for the site? Keep in mind it is the custom code that is conditional, not necessarily the plug ins
Even if there way a way to create a JavaScript file for each area, how
would that be referenced within the main layout?
Is it best to load the JavaScript include files at the end of the include file?
What is the effect of minification on performance and would it benefit the custom code file?
Any advice would be appreciated.
First, use bundling. Give BundleConfig.cs under the App_Start folder in your project a gander. By simply minifying and bundling all your JS together, it's sometimes inconsequential that certain code is not actually being used on the current page (the savings you gain from having one cached JS file that every page uses is sometimes better than loading a new different bit of JS on each page.)
If you need more fine grained control, you can use something like Require.js. You essentially write your JS in modules that depend on other modules to run (all of your plugins, jQuery, etc. become "modules" in this scenario). You'll need to manually minify and combine your JS as much as logically possible, but this will allow you to integrate various scripts together without having to worry about load order and missing dependencies.
As a side note, I would respectfully disagree with Kevin B. If maintainability dictates that your JS has to be in the head, I would say that's a symptom of a larger problem with your code design. The only good reason to add JS in the head is when it's essential that the JS be run before the page is rendered. A good example is Modernizr, which for one adds classes to the html element to allow you to specify different styles and such depending on whether certain features are available in the user's browser or in the case of IE, what version the user is running. Without loading in the head, your style would changed after page load leading to flashes of unstyled content and such. Other than situations like these, all JS should go before the closing body tag, as JS is blocking: the browser will completely stop what it's doing and all rendering of the page, and run the script completely before continuing. Too much of this in the head, and your users stare at a blank page for far too long.
Also all script (and CSS for that matter) should be minified. There's no good reason not to, and the difference in bytes the user has to download is often quite dramatic. Especially in this day and age of mobile-everything and far-too-limited data plans, every byte truly does count.

Loading a single javascript file from multiple files

I'm trying to load a single javascript in pieces by calling the javascript from external separate files, and was wondering the best way to go about doing this. Specifically, this is a just a basic google maps page, and I want to organize the code a little better. I'm hoping to split the marker variables up into groups and store those groups of variables in separate files, then call those files within the main javascript header of the page. I want to restrict this code to just html and javascript to maintan its simplicity for the purpose of future updates by individuals less than knowledgeable in this area. I don't do a whole lot of coding with JavaScript so, if there already is a built-in function for this, that would be great. This is purely aesthetic, just to make the code a little cleaner. Any help or suggestions would be appreciated. Thanks.
If I understand you right, you don't want to call one JavaScript files from several another JavaScript files. You want just save some groups of variables. Well, you can save it - with a server-side database or, may be, with http://www.w3.org/TR/webstorage/ or http://www.w3.org/TR/IndexedDB/
You can add references to external files:
<html>
<head>
<script type="text/javascript" src="colorGradient.js"></script>
<script type="text/javascript" src="xpath.js"></script>
<script type="text/javascript" src="kml2.js"></script>
<style type="text/css"> ... </script>
</head>
<body>
....
</body>
</html>
You can try a "feature loading" and/or "on-demand javascript loading" framework. Since you're trying to use Google maps, I would recommend you use the Google Loader API which works very closely to what you're seeking.
for example: With a simply JS you can do the following....
<script type="text/javascript">
google.load("search", "1");
google.load("jquery", "1.4.2");
google.load("jqueryui", "1.7.2");
</script>
... and it will load the multiple files.
Splitting up you code for your development is a good idea. There for, there are a lot of frameworks to help you organize your code with the help of MVC and psudo MVC models.
Try:
http://maccman.github.com/spine/
or
http://documentcloud.github.com/backbone/
But what prevents you from having everything in one file on the production environment?
Its easier on the server requests. And you want to integrate this in your build process anyway...
But if you insist in on adding them to the DOM you can do this of course:
document.write(unescape('%3Cscript src="yourfile.js"%3E%3C/script%3E'))
this will add
<script src="yourfile.js"></script>
to your dom
If I understand your question correctly, you would like to split up a single script into multiple .js files. As far as I know, this should work fine as long as you include a tag to load each file. You may need to load the files in order (i.e. don't include a file that calls a function that has not been difeined yet).
However, be aware that splitting up your script will result in more calls to the server, which will slow down page load. In most cases, just including a few scripts won't even make a noticible difference in load time.

How to Include JavaScript on a Public Facing Website?

I am building a public facing website and I am using a lot of jQuery and jQueryUI. What I have noticed is that most site on internet that use jQuery and jQueryUI don't have code like this in their pages.
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(event){
alert("Thanks for visiting!");
});
$( "input:submit" ).button();
});
</script>
I know this is a simplistic example but most sites, for example SO have only one obfuscated js file included for all the pages. It doesn't even seem like they use $(document).ready anywhere. On my current site it seems like I would need to include a js file for each page. My question is how is it suppose to be done and is there a best practice on how to use/include javascript in a page?
You wouldn't see the famous document.ready because most of the code is compressed usually into one big file for caching purposes. Just include your js at the end of the body like:
<script type="text/javascript" src="site.js"></script>
so this can be cached once and for all for every page.
According to W3C you could put scripts almost anywhere: http://www.w3schools.com/js/js_whereto.asp
So where should you put them?
Ege is right to say that you should put them as far down the page as possible because it will enable the browser to load more in parallel up front before it gets to the 'blocking' scripts. See here for more detail: http://developer.yahoo.com/performance/rules.html#js_bottom
Also, it is nearly always a good idea to put your scripts (and CSS) into external files so the browser can cache them tus saving the user from having to download them with the page each time.
Personally, I always use a CDN for script frameworks such as jQuery and the like as they can deliver external resources quicker than you probably can. Also the likelyhood of the browser having already cached jQuery for another site from the same CDN is far more likely. More detail here: http://code.google.com/apis/libraries/devguide.html
Finally, there's nothing wrong with using $(document).ready, but just be aware that this could affect the site's responsiveness and its pros may not outweight its cons. Again, more detail here: http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/
Hope this helped.
Whether you include the 'site.js' file at the top or bottom doesn't matter, unless your javascript is doing document.write to put something on the page. Then of course at the top would be desired. Some like it at the bottom so that the rest of the page will load before downloading the js file, which can sometimes delay the page load if it is a large file.

Categories

Resources