Is assigning html to javascript variable a good practice? - javascript

I am a newbie to html/css/javascript and code like this really scares me:
http://code.google.com/apis/maps/documentation/javascript/overlays.html#InfoWindows
Is assigning html to javascript variable a good practice? or I hope there is a substitute.

There is nothing wrong with it. After all, it is really no different then typing the same thing outside of the javascript block.
I do however find, that the formatting and the likes can be annoying. On use JQuery a fair bit, and depending on what I might be doing I might use a .html() or .clone() method to create html form another element.
JQuery also has a template plugin which when used does allow for you to get slightly better formatting, and you can also specify dynamic values. Which is great for creating dynamic tables that update with Ajax for example.
Another side note, the fact that example you gave was on a Google site, would usually be enough to convince me it is OK to do ;)

There's nothing bad in it. People have been doing this since there was a thing called DHTML :-)
AFAIK, this is one of the most performant ways to build a part of document (later to be inserted to DOM or whatever).

In this case you have to, since google Maps API requires explicitly to pass a HTML content (and not a reference to some hidden element in page or loaded via ajax).
This don't mean it's a bad practice: for example, I always use a HTML string along with some custom template system, so that I can pass infowindow HTML in a loop, changing dynamically some chunks of markup with data retrieved by a JSON.
Anyway you can still use an element into the DOM and then pass its outerHTML string to the API if this makes your application more performant with an improved maintainability

Related

Best (or correct) way to use JavaScript with C#/Razor?

What is the best and maybe correct way of mising JavaScript code with Razor?
At the moment i put my JavaScript code in an external JavaScript file "external.js" but there i have the problem that i can not access the C# variables of my model directly (i can do it, but it makes the whole thing a little bit complicated). This only works with Razor-Syntax #Model.Variable when i embed my JavaScript Code inside the view in the -Section/Tags.
So i thought about this situation and don't find an answer. I read and thought it would be the best to put all JavaScript code in one file, so that the browser loads the whole stuff only one time and then read out of the cache (Performance). But could it be better to write the JavaScript code inside each View instead of putting into one huge file?
Putting your Javascript directly into your view isn't going to affect the load of your page in any significant manner (unless your Javascript really is a behemoth).
It will be transported (and subsequently cached) when the view is requested.
If you're wanting to use your razor variables directly in Javascript, then having it in the view is your most sensible option
That is, of course, the view is intended to be used as a partial - in which case you probably want to rethink the design

Why use CakePHP's JsHelper?

I'm just starting with CakePHP and was wondering if someone could explain the true benefit of using its JsHelper over coding regular static jQuery and JS. So far, I don't really see how the helper would make creating scripts easier or faster.
for the same reason I wrote my GoogleMaps Helper ;)
the basic idea is that you can use the same language (php in this case) as the rest of the application and you can pass in any php option arrays and arrays holding data values and the helper is supposed to cake care of it.
it is similar to cakephp as a wrapper for php. it wraps your code and can help keep it dry.
don't get my wrong - i never ever used the js/ajax helper myself.
but I can understand why some want to chose it over writing JS themselves.
in some cases the output can even be more "correct" (if you don't know about the potential problems). for example the IE bug:
if you output {} options yourself and forget to remove the last , it will not run in IE6 etc. that can't happen with the helpers as wrapper - at least it shoudnt ;)
so with the helper it either doesnt run at all or runs as a team of skilled developers designed it to work.
especially for not so skilled developers this is usually a win-win situation: fast and more reliable. you can always start to switch to manual stuff later on (if you see the actual JS output and start to understand it).
also - when any of the js methods need to change for some reason your way of using the helper usually doesn't. if you don't use the abstraction you might find yourself in the need to manually adjust all occurrences.
As like any Helper, the JsHelper is a way to parse stuff into your view in a simplified way. But putting in "raw" JS/jQuery code into your view would work just fine by using $this->Html->scriptBlock for example.
There is not a real benefit I could think of other than if jQuery would ever change the syntax of a specific function, you wouldn't need to adjust your code when using the JsHelper, since the core then needs that update to be implemented, rather than you having to change all your "raw" JS code throughout all of your views.
JsHelper is like scaffolding: comes very handy if you need just the basic stuff, and only the basic stuff. That is, ajaxify a pagination or some elements.
But beyond that, it is better to write your own code, because you will need things as you need them, and not how the helper is aligned by default.
As everything else in a framework: it is a tool. Check your requirements and use the best tools available.

jQuery - some beginner questions

I'm a very beginner to jQuery, and I'm having some basic questions:
Is it advisable to use jQuery whenever it is possible to replace something by using it? For example, is it prudent to bind all events to elements using it, instead of through HTML?
Is it better to host the jQuery .js file and all other relevant files (like JQuery UI) myself, or is it perhaps a better choice to use Google's link (they seem to host it for others too)?
When it comes to executing a script when the page is done loading, what way is preferred?
$(document).ready(function() {})
$(function() {})
$().ready(function() {})
They seem to all do the same thing, but what is the preferred way of scripting?
Yes. This way your JS is cleanly separated from your html. You can look at your file and in one glance, see how it is affecting your HTML. If it was embedded in the HTML, you would have to look for onClick, onLoad etc and it can get pretty messy for large applications.
Client browsers will cache files, so if you use the google version of JQuery, it will not have to download it off your server. Saving you bandwidth.
$(document).ready(function() {}) Is the preferred choice. $(function() {}) Just defines the block for execution, it will only execute after the page is ready if it is the last thing on the page to get executed.
1.) Yes and No. It is considered best practice to bind events unobtrusive regardless of using jQuery or not (this means, strictly separate javascript, html and any other language). Since jQuery allows to easily bind events it's a better way to use inline-handlers.
2.) You should use a CDN (like google) to deliver static files like jQuery for Caching purposes + they have a huge server network which may even be faster than your own host.
3.) I would stick to the first two calls. Anyway, basically they all will do it, but the best readability probably has $(document).ready(function() {});
1) Keep all your event binding in your script. This makes it easy to change later. You'll also appreciate having a single place to look for all event-related logic.
2) This has been answered very well already.
3) I prefer #2 for its brevity, but really the ideal way to do it is like this:
jQuery(function($) {
// Your code using failsafe $ alias here...
});
That avoid conflicts if you are using other frameworks that define $.
1: no this is completely up to you. generally jQuery incurs a performance penalty, because it is an extra layer of abstraction. Only use it, if you feel it helps you do your job easier. However, unless you truely need to optimize for performance the benefit in using it will far outway the cost. jQuery gives you tried and tested crossbrowser compatibility, which, if you wish to cater to all the different browsers out there, can be a costly affair to implement yourself.
2: Use Googles version: that way there is a chance that your users already have it cached and don't need to load it again from your site.
3: 2nd option, the shortcut is very widely used to a point where i'd say it's prefered even though 1st option is nice and specific. I'd never use 3rd option
For the 3d point, none of them. it is generally recommended, for performance reasons, to place your scripts just before the closing </body> tag. Thus you will not need to wait for the ready event: at this stage, the page is already loaded.
Check Jquery Cookbox (O'Reilly), Chapter 1.2: Executing jQuery/JavaScript Coded Ater DOM Has Loaded but Before Complete Page Load (that book is a must read all in all)
To have a quick idea about this technique, check Move jQuery to the end of body tag? (there are many other posts on SO about this subject)
I personally don't subscribe to the "cleanly separate JS from HTML" philosophy. I rarely see real world use cases where that has any benefit. Separating HTML from JS often leads to buttons that say "click here to do X" in the HTML but do nothing unless the appropriate javascript is with them. Kind of misses the point.
With the case of jQuery and events... I find it much easier to debug an app if I can inspect an HTML button in firebug and see what that button does (by looking at the onclick attribute).
Using the google version can aid with caching, but don't link directly to jquery.com. We did that here once and they went down, took us with them.

jQuery: Templating data

I have a unique situation where I'm building a site that will call data via AJAX and load it into "containers" (basically just divs styled and arranged according to elements retrieved from the AJAX callback).
I'm not sure how many of these unique container types will be created (styled and rendered) when all is said and done, so I'm looking for a solution that will allow me to store containers in a separate file(s), load them dynamically as they are needed, populate the content, and rendered them on page.
I'm not sure if I should write my own loading/template solution or use an existing JavaScript template engine (e.g.: Pure).
The reason I'm hesitant to use an existing JavaScript template solution is they all seem focused on binding and looping on existing page elements, whereas I'm more concerned with the ability to load-up and binding to dynamic content.
You might want to give jQote a try, it's the most powerful jQuery templating engine as it let's you use scripting inside your templates.
Go check it out, it'll suit your needs, I promise.
http://aefxx.com/jquery-plugins/jqote
After starting with JST, we moved to EJS:
http://embeddedjs.com/
It's more powerful, syntactically simpler, and you can put your templates in different files.
The website is pretty nice too.
I found http://code.google.com/p/trimpath/wiki/JavaScriptTemplates pretty useful for this.
I am planning to use jTemplates for a future project that will need to do something like this, it is very fast and has a nice jQuery plugin

JSONML vs. InnerHTML vs.?

First of all, am I the only person using JSONML? And second of all, would you recommend using JSONML for inserting dynamic HTML or is InnerHTML more efficient?
Bare in mind that (in IE) not every innerHTML is writable (innerHTML isn't standar compilant anyway). So closer you come to appending nodes rather then inserting html, better you are. As far as I can see, jsonml thingie creates DOM elements whch is nice. I can only sugest you to make some huge dataset, insert it in two different ways and mesure performance yourself.
While superficially used to perform similar tasks, JsonML and innerHTML are quite different beasts.
innerHTML requires you to have all the markup exactly as you want it ready to go, meaning that either the server is rendering the markup, or you are performing expensive string concatenations in JavaScript.
JsonML opens the door to client-side templating through JBST which means that your template is converted from HTML markup into a JavaScript template at build time. At runtime, you simply supply the data and you end up with DOM elements to be inserted or to replace an existing element (something innerHTML cannot easily do without extra DOM creation). Rebinding only requires requesting additional data, not the entire re-rendered markup. This is where large performance gains can be made as the markup can be requested/cached separately from the data.
For simplicity, innerHTML has been the preferred method for the HTML-Message pattern style of Ajax. But tool-sets like JsonFx can make using JsonML and JBST just as easy while delivering a full browser-side templating Ajax pattern.
JsonML and the connected libraries (templating, etc.) seem to offer an efficient way of generating dynamic HTML on the client side.
When I say efficient I mean, I mean that the programmer does not waste time or effort while completing his task. But I am not sure if you meant to ask whether using innerHTML is faster and requires less resources on the client side.

Categories

Resources