HTML/JS dynamic loading from JQuery - javascript

In my single-page JS-app, I've decided to dinamically load portions of HTML/JS in a JIT manner. I found 2 ways to do it, using JQuery:
First:
$("#target_div").load("html_and_js.html");
// the HTML file contains both HTML` and the corresponding JS code
Second:
$("#target_div").load("thtml_only.html", function() {
$.getScript('js/js_only.js');
}); // now the JS is kept separatelly from HTML
I would like to know your experiences and opinions regarding pros/cons of both approaches.
As I'm building an single-page AJAX app, I am particularly interested in the following aspects:
Browswer performance if the large number of those dynamic loadings/removings are made - how much memory the modern browsers reserve for DOM?
is the DOM structure kept safe and clean?
when the corresponding DIV (#target_div in my example) is removed - is the JS also removed from the browser memory? Eventual memory leaks?
Every opinion is highely appreciated.

From an architecture perspective you're separating out your presentation layer from business logic that may be held in the javascript - always good to do.
Separating your javascript into a separate file allows you to minify it easier, and re-use any of the functions that you develop into the javascript file.
Also, in the second option, the javascript will only get loaded once the html has completely loaded. Although as a rule of thumb I always recommend javascript goes as close to the end of the HTML document as possible, there are some (albeit rare) occasions where you need some portions of your javscript to run during the page load, not after it, and therefore the second approach (loading html first, then javascript on complete) wouldn't allow this javascript to run. Though... it could allow you to put the rare javscript that needs to be run into your HTML-only page (granted making it not-so-HTML-only), and keep the rest of the javascript separate for running at the end of the page.
Just my opinions, hope they help,
Kurt

Related

If grouping front-end code helps reduce requests, why aren't more websites written on one html document?

I guess what I'm asking is that if grouping JavaScript is considered good practice, why don't more websites place the JavaScript and CSS directly into one HTML document?
why don't more websites place the JavaScript and CSS directly into one HTML document
Individual file caching.
External files have the advantage of being cached. Since scripts and styles rarely change (static) and/or are shared between pages, it's better to just separate them from the page making the page lighter.
Instead of downloading 500kb of page data with embedded JS and CSS, why not load 5kb of the page, and load from the cache the 495kb worth of JS and CSS - saves you 495kb of bandwidth and avoids an additional 2 HTTP requests.
Although you could embed JS and CSS into the page, the page will most likely be dynamic. This will make the page load a new copy all the time, making each request very heavy.
Modular code
Imagine a WordPress site. They are built using a tom of widgets made by different developers around the world. Handling that many code stuffed in one page is possible, but unimaginable.
if some code just short circuited or just didn't work on your site, it's easier to take out that code linking the external file, rather than scouring the page for the related code and possibly accidentally remove code from another widget.
Separation of concerns
It's also best practice to separate HTML from CSS and JS. That way, it's not spaghetti you are dealing with.
When you have a lot of code in a single document, it's harder to work with the code because you need more time to find the necessary string to change.
That is why it's good practice to divide code into separate files, with each of them solving its own special task, and then include them in code where it's necessary.
However, you can a write script which will join your files from the development version, which has many files, to a release version, which has fewer files, but this brings two problems:
People are often lazy to do additional coding to create this script and then change it when the structure of your project becomes more complex.
If you find a bug or add a small feature, you will need to rebuild your project again both in developed and release versions.
They separated them so that multiple webpages can use the same file. When you change a single file, multiple pages can aromatically updated also. In addition, big HTML file will cause a long time to download.

Embedding vs. including Javascript for DOM interaction?

Every beginners guide to Javascript talks about the evils of embedded scripts.
And I get it: definitely good advice for novices who have no concept of modular design. But every rule has an exception, and since I'm fairly new at web development (but not development in general) I want to ask if the following is a good exception:
I'm building a web application using MVC on the server-side (Django, for the record), and Require.js on the client-side to manage application logic scripts. I'm careful to keep these scripts DOM-agnostic.
It makes sense to me to embed the remaining DOM-interacting code directly in the server-side HTML templates that are defining that DOM. Creating separate JS files that are so minimal and tightly coupled with the content of the templates just feels unnecessary. Am I wrong?
Assuming you've got all application logic tucked away nicely in external files, is it really so bad to sneak a few lines of jQuery in with your HTML to hook that logic up to the DOM?
If you've got JS that applies to only one page and there's not very much of it then yes, I would put it directly in the page rather than as a separate JS include.
If you have a lot of JS that applies to only one page then a separate JS include gives you the advantage that (after the first request) it will sit in the browser cache rather than being downloaded every time a user refreshes that page. So in that case I'd probably stick with the external JS file.
Having made the decision to include JS in a particular html page, I prefer to include it all as a single block either in the head or at the end of the body - I don't want to have to scan through the html looking for multiple small script blocks buried in the markup. Also if I later decide to move the script to an external file it is easy to do so.
See this on where it is going particularly comment around Angular js from google referred to
http://blog.stevensanderson.com/2012/08/01/rich-javascript-applications-the-seven-frameworks-throne-of-js-2012/
See this Comparison http://engineering.linkedin.com/frontend/client-side-templating-throwdown-mustache-handlebars-dustjs-and-more thorough test and comparison
It appears DOM Templates maybe the future. And for my mind better to deal with in terms of debugging.

Running code just before </body> instead of waiting for DOM ready/DOMcontentloaded event

Is there any drawback to putting code (which will interact with the DOM, adding event listeners and so on) just before the closing </body> tag?
<!-- all the HTML comes before this -->
(function() {
do_stuff_with_the_DOM();
})();
</body>
It seems to work in my own tests, but I never see this method used in tutorials, code examples, or other people's projects. Is there a reason not to do it? Are there edge cases that only seem to pop up when you begin using this in production and see many page views across a variety of browsers?
My project doesn't use jQuery or any other toolkit, and I'm aware of the alternatives that mimic jQuery's $(document).ready() functionality. Do I really need to use one of those? (It should go without saying, but I'm looking to run the code before window.load.)
Note that the code I want to run (do_stuff_with_the_DOM() in the example above) would be defined in an external script file, if that makes a difference.
You should put your JavaScript code in the place that makes the most sense for what it needs to do. In most cases, you need your js to attach events to DOM objects, which is hard to imagine if those DOM objects don't exist when the js is running. So putting it at the bottom of the html is a sensible, simple, and common approach. Is it the best? That's arguable.
Another approach is to attach your JavaScript to the various events that different browsers fire when the DOM is fully loaded. There is nothing wrong with this, although detractors don't like that it's often done in a way that requires an additional blocking HTTP request in the head element.
Event delegation offers a third approach that lets you attach events to parent elements (such as body) very early, and when appropriate child events exist the events will fire as if they had been attached to those elements all along. It's a very cool approach with theoretically the best early-loading performance of any of the above, but has pitfalls in that not all events bubble all the way to the top, like you might expect, and that it often tempts you to separate your JavaScript into multiple chunks, which can violate separation of content and behavior.
In General
Putting code just before </body> should always be the aim.
Its highly recommended, as the download of scripts (if requesting external JavaScript files) blocks parallel downloading (i.e. whilst a script is downloading, nothing else - be it another script or an image for example - can be downloaded at the same time).
The only time you should have an issue with this, is in something like a poor CMS system where you need to have jQuery in-place in the <head> in order for some of its scripts to work.
Using inline JavaScript
Adding inline JavaScript (or inline CSS code) to a page is generally considered bad practice as, for one, its a merging of concerns (i.e. you no longer have true separation between HTML/CSS/JS).
I cannot think of a negative performance issue if you did have all your code inlined - indeed Google use this as a practice (they load all their JavaScript in a bit comment (so that it isn't parsed) and then eval() elements of this blob of "text" as and when they need to.
I would note however, that its unlikely nowadays that you'll have many pages that don't at some point have a requirement on at least one external JavaScript file (be that JQuery, Mootools, Underscore of Backbone). In which case, as you will always have at least one external file (unless you're going to Google route), then you might as well put both external references AND inline code together... at the bottom. Creating consistency.
References
Yahoo Developer Network best practices
Google Page Speed - Defer the loading of JavaScript

Minification for Css/Js - right way?

In my project each page has a bunch of dependent Javascript and Css. Whilst developing I just dumped this code right into the page but now I'm looking to clean it up...
it appears that the general approach out there is to package all the Javascript/CSS for an application into two big files that get minimised.
This approach has the benefit that it reduces bandwidth since all the front-end code gets pulled in just once from the server... however, I'm concerned I will be increasing the memory footprint of the application by defining a whole ton of functions for each page that I don't actually need - which is why I had them on a per-page basis to begin with.
is that something anyone else cares about or is there some way to manage this issue?
yes, I have thought of doing conditional function creation since I need to run code conditionally for each page anyway - though that starts to get a bit hackish in my view.
also, is there much cost to defining a whole ton of Css that is never used?
Serving the javascript/CSS in one big hit for the application, allows the browser to cache all it needs for all your pages. If the standard use case for your site is that users will stay and navigate around for a while then this is a good option to use.
If, however, you wish your landing page to load quickly, since there is a chance that the user will navigate away, consider only serving the CSS/javascript required for this page.
In terms of a performance overhead of a large CSS file - there will be none that is noticeable. All modern browsers are highly optimised for applying styles.
As for your javascript - try not to use conditional function creation, conditional namespace creation is acceptable and required, but your functions should be declared only in one place.
The biggest thing you can do for bandwidth is make sure your server is compressing output. Any static document type should be compressed (html, js, css, etc.).
For instance the jQuery Core goes from approx. 90KB to 30KB only because of the compressed output the server is sending to browsers.
If you take into account the compression, then you have to create some mammoth custom JS includes to really need to split-up your JS files.
I really like minifying and obfuscating my code because I can put my documentation right into the un-minified version and then the minification process removes all the comments for the production environment.
One approach would be to have all the shared javascript minified and compressed into one file and served out on each page. Then the page-specific javascript can be compressed/minified to its own files (although I would consider putting any very common page's javascript into the main javascript file).
I've always been in the habit of compressing/minifying all of the CSS into one file, rather than separate files for each page. This is because some of the page-specific files can be very small, and ideally we share as much css across the site as possible.
Like Jasper mentioned the most important thing would be to make sure that your sever is GZIPing the static resources (such as javascript and css).
If you have a lot of javascript code you can take a look on asynchronous loading of js files.
Some large project like ExtJs or Qooxdoo have build in loaders to load only required code, but here is a lot of libs which simplify this, and you can use in your project (e.g. head.js, LAB.js).
Thanks to them you can build application which loads only necessary files, not whole javascript code which in case of big apps can be a heavy stuff for browser.

Is there any good reason for javascript to be inline

I've been building a site. At some stage I noticed that IE display was a little broken and Chrome had all but rendered nothing but the body tag (empty), and FF all looked good.
After throwing my keyboard around the room and bashing my head against my mouse, I discovered the problem. I had left (don't ask how or why, must have been some lightning speed cut and paste error) an HTML comment unclosed in an inline script block.
<script type="text/javascript">
<!--
...
</script>
I'm guessing (not tested) the problem would have either not come up, or manifested itself in a far more noticeable way if the script was external. So anyways, I got to thinking, is there ever a time when you have a really good reason to write inline script??
No. Write Unobtrusive Javascript.
If you want your Javascript to run as early as possible, it might make sense to include inline Javascript, since it will run before any other HTTP requests have necessarily completed.
And in some cases, you're including Javascript from a 3rd party provider and you don't really have a choice. Certain ad systems, as well as Google Analytics, spring to mind.
If the script must be dynamically generated (say by a PHP or ASP.NET MVC page) would be one reason to have it inline :-)
Depends on how much JS do you plan to write. If you're writing many support routines (lots of validation checks, text processing, animation and effects) then it makes sense to have the code in a separate file. This allows code reuse and removes a lot of junk from your HTML page.
On the other hand, there is no need to put 10 lines of code, or a single function (a refresh JS comes to mind) in a separate file. It will also load slightly faster, since the browser does not need to make an additional HTTP request to download the separate JS file.
Most XSS vulnerabilities can only be exploited using inline javascript.
It's not necessarily enough of a reason, but the pages will load faster. To this end, sometimes, even when you write the script in another file, you want it to show up as inline on the client side.
I sometimes place javascript inline in pages that get partially reloaded (to bind some events to newly added form-fields for example) and / or pages that use some unique javascript that I will not use on any other page.
Having many external scripts can ultimately slow down the page as the browser must call each file separately. Combining the JavaScript into one file or into the page itself can sometimes alleviate this problem.
On the other hand, I believe the browser may cache a script file once it's been called for the first time so if you have a lot of the same code across your site, external is the way to go.
I work a good deal in something called Flex, which combines XML and ActionScript to create the final bytecode. It is ALWAYS best practice to separate the two as much as possible. That way, you can very clearly and easily separate the View (the HTML or MXML in my case) from the Controller (the script)
It also means that you do not have to worry about looking through five files for one line of code -- all of your code is in one place.
File caching is the reason to have external js and css files. Even if you only have one HTML page, this page is likely to be updated often and so will be downloaded by the browser as often. If the js (and css) are in the HTML page, that too will be downloaded often. Keeping them separate will keep the HTML file smaller and will download faster. The js and css files will have been cached so will not be continually downloaded. That is assuming these files are not updated very often.

Categories

Resources