Dynamically printing javascript - javascript

I recently ran into a situation where it made sense (at first at least) to have my server-side code not only "print" html, but also some of the javascript on the page (basically making the dynamic browser code dynamic itself). I'm just wondering if there is sometimes a valid need for this or if this can usually be avoided...basically from a theoretical perspective.
Update:
Just to give an idea of what I'm doing. I have a js function which needs to have several (the number is determined by a server-side variable) statements which are generating DOM elements using jQuery. These elements are then being added to the page. So. I am using a server-side loop to loop over the number of elements in my object and inside of this loop (which also happens to be inside of a js function) I am aggregating all of these statements.
Oh and these dom elements are being retreived from an xhr (so the number of xhr requests is itself a server-side dependency) and then processed using jQuery..which helps explain why im not just printing the static html to begin with. Sounds kind of ridiculous I'm sure, but its a complicated UI..still I'm open to criticism.

I can smell some code smell here... if you're having to generate code, it probably means one of:
you are generating code that does different things in different situations
you are generating same kind of functionality, only on different things.
In case 1, your code is trying to do too much. Break your responsibilities into smaller pieces.
In case 2, your code is not generic enough.

Yes there is sometimes a need and it is done often.
Here is a simple usage in an Asp.net like syntax
function SayHi( ){
alert( "Hello <%= UserName %>");
}

Just a suggestion. If your server-side is generating HTML/Javascript, then you're letting view-side logic creep into your server-side. This violates separation of concern if you're following an MVC-style architecture. Why not use a taglib (or something of that nature) or send JSON from the server-side?

One usefull feature is to obfuscate your javascript on the fly.. When combined with a caching mechanism it might actually be useful. But in my opinion javascript generation should be avoided and all serverside variables should be handed to the script from the templates (on class or function init) or retrieved using XMLHTTP requests.

If your application generates javascript code only for data (eq. you want to use data from sql in js), the better practice is to use JSON.

Yes, sometimes for some specific task it may be easier to generate javascript on the fly in a bit complex way, like in rails rjs templates or jsonp responses.
However, with javascript libraries and approaches getting better and better, the need for this is becoming less, a simple example you may have needed to decide on a page whether to loop some elements and apply something or hide another single element, with jquery and other libraries, or even one's own function that handles some complex situation, you can achieve this with a simple condition and a call.

Related

Javascript function pass object or use data attributes?

I'm wondering which of the following would be the best way to pass server data and use it in a function, especially if the function is to be used by a component
Method 1
function doSomething(elm, serverTime) {
// Do something
}
<script>
doSomething('foo', '<% php server time %>');
</script>
vs
Method 2
<div id="foo" data-server-time="<% php server time %>"></div>
function doSomething(foo) {
var serverTime = getElementById("server-time").dataset.servertime;
// Do something
}
<script>
doSomething('foo');
</script>
Method 3
Other suggestions?
Would like to do something like the following but not sure how?
document.getElementById("foo").doSomething() ?
For me, case 1 would be better.
code would have less coupling
code would not use global vars (document.getElementById)
you could reuse your function in other places that do not have DOM, like in the server.
I would argue in this case the 1st is better in this simple example because sever time isn't really attached to any specific div element.
Just make sure no matter what you do that there are no XSS security holes.
You are at a crossroads looking for common practice, to which one isn't more prevalent over another. Any great sage may tell you, which you choose isn't as important as making the same choice again; that is, be consistent.
Depending on the type of information, I would either pass it in the:
HTTP header (e.g., via HTTP Cookie)
Querystring (if redirection is used)
External JSON file (e.g., server.json), loaded via JS
Embedded JSON object (e.g., window.SERVER = {'server_time': <%php ...%>};)
In your case, keeping it closer to the JavaScript makes more sense and is easier to maintain, if the JS is the main place you're working. Therefore, Method 1 is both cleaner and easier to make changes in the future. Method 2, would require sifting through the HTML and making sure you are modifying the correct line.
Though, I'm somewhat partial to keeping server data as an external JSON, or embedded JSON object. So if you needed to track other server data/metadata, it's easy to add to it.
I would argue that all of them are the same and depending on your coding manner, they woulh have the same performance performand.
Let's not forget that nowadays, the most common way is to attach event listeners to elements (jQuery, Angular and .., use heavily event listeners).

Using Script Tags As A Template System

** Revised **
I made this basic example which I believe is evicence that JavaScript may be useful as it's own template engine:
http://jsfiddle.net/julienetienne/u6akrx7j/
<script>talk[0].text('Hello World!');</script>
It's just a simple example but as you can see there are many possibilities eg.
It doesn't necessarily have to detect the tag nodes in that manner, it could do it by class, id. It is also possible to obtain the script node of the function,
you could simply print variables like p('Page Title');
A self closing list of elements could be similar to e.g. li('', menu);
And you could clearly build up other complex data sets as you can with any other common template engine.
Before this edit I made the mistake of comparing it to PHP. I'm actually considering it more of an alternative to e.g. handlebars, underscore, moustache, dust and similar.
But before I get to excited I would really like to know if there are any issues in regards to using in this way. (I'm not concerned with novice best practices).
The benefits of an organic template system seems quite apparent. The biggest advantage is that there is no syntax to learn and it's cleaner than seeing %{{foobar}}% like markings.
Considering my example is just a tiny minimalistic concept, please tell me the drawbacks of a system like this compared to common template engines.
Thanks
It looks like it's a PHP-style templating system, but it is apparently not:
In the fiddle the script parts could be written anywhere in the page.
The part that defines the position of the texts to be inserted into the DOM is defined by the line var talk = document.getElementsByTagName('div'); and the structure of the HTML.
If you'd use more div than the ones already there the texts will appear at a totally different (and supposedly wrong) position.
The disavantage will thus be, that you can't use the system independently of the underlying markup. That makes it different from a use case in PHP, where you can echo the variables by defining their position in the markup.
Have a look at Angular or similar front end frameworks, if you are looking for a way how to implement a templating system.

JavaScript Hacking

I am trying to figure out any and all ways to prevent CSS modification and DOM modification of specific elements. I understand this might not be completely possible or that a talented developer could get around it, however, I am not so concerned about people potentially getting around it, I just want to stop newbies. In particular those using jQuery. An example would be to delete certain properties on prototype objects etc..
But why you need/want this? If you want to "protect" your code, you can use some JavaScript minifier as Google Closure Compiler or YUI compressor. They will rewrite your script and it will be difficult to read by a human. Nowadays, with tools like Firebug and Grease Monkey it's almost impossible to do what you want.
Don't use CSS or JavaScript :p Depend completely on server side checks etc.
You cannot stop anyone from messing with your javascript or your objects in the page. The way the browser is designed, your code and objects in your page are simply not protected. Everything from bookmarklets to javascript entered at a console to browser plug-ins can mess with your page and code and variables. That is the architecture of a browser.
What you can do is make things a little more difficult such that a little more work is required for some things. Here are a couple of things you could do:
Obfuscating/compressing/minimizing your code will do things like remove comments, remove whitespace, remove some linebreaks, shorten variable names, etc... That does not prevent anyone from modifying things, but does make it more work to understand and figure out.
Putting variables inside closures and not using globals. This makes it harder to directly modify variables from outside of your scripts.
Keep all important data and secrets on your server. Use ajax calls to ask the server to carry out operations using that data or secrets such that the important information is never available in the browser client.
You cannot keep anyone from modifying the DOM. There simply are no protections against that. Your code can check the DOM and refuse to operate if the DOM has been messed with in non-standard ways. But, of course, the code would then be modified to remove that check too.
If you are looking for a jquery specific solution a crude approach will involve altering the jQuery ($) function and replacing it with a custom one that delegates to the original function only if the provided selector does not match the element you want to secure.
(function(){
jQueryOrig = jQuery;
window.jQuery = window.$ = function(){
if (jQueryOrig("#secure").is(arguments[0])) {
throw new Error("Security breach");
} else return jQueryOrig.apply(this, arguments);
}
}());
Of course people using direct DOM manipulation would not be affected.
Also, if you are actually including arbitrary third party code in your production code, you should take a look at Caja ( http://code.google.com/p/google-caja/ ), which limits users to a subset of javascript capabilities. There is a good explanation regarding Caja here : http://due-diligence.typepad.com/blog/2008/04/web-20-investor.html .
This is possible but requires that the JS file to always be loaded from your server. Using observers you can lock CSS properties and using the on DOM remove/add listeners you can lock it to a parent. This will be enough to discourage most modification.
You can actually go a step further and modify core javascript functions making it nearly impossible to modify the DOM without loading the JS file locally or through a proxy. Further security can be added by doing additional domain checks to make sure the JS file is loaded from where it is supposed to be loaded from.
You can make everything in Flash. In Chrome, there's even a bug that prevents users from opening a console if the flash element has focus (not sure how exactly this works, but you can see an example at http://www.twist-cube.com or http://www.gotmilk.com). Even if users do manage to get a console open (which isn't that hard...), still about all you can do is change the shape of the element.

Is there anything I can't do with mustache?

I'm evaluating http://github.com/janl/mustache.js
and I'm thinking about how it will work in general over time with a time. If I just build a giant object, is mustache sufficient to transform it into any form of HTML?
So, my question is. Is there anything that mustache can't do?
(My thought is that it is just tree transformation from JSON to HTML, but I'm not sure how to validate that or gain enough confidence to bet against it)
further clarification
Suppose that all I had was a giant object and then I gave to a mustache template in one iteration; is there anything in HTML that can't be expressed in mustache via its language.
Since Mustache is just a template language in JavaScript, you can do anything you can already do in JavaScript, and JavaScript is Turing complete. So no, there's nothing that you can't do in Mustache; in fact, there's nothing you can do in Mustache that you can't do yourself in JavaScript, it just makes some things more convenient.
When evaluating something like this, instead of determining what it can and can't do, it's more useful to ask "does it make the things that I need to do easy" and "does it make the mistakes I want to avoid hard to make."
For instance, one way to evaluate it would be whether it makes it easy to avoid cross-site scripting (XSS) attacks. According to the documentation "mustache.js does escape all values when using the standard double mustache syntax", so it sounds like it does do a good job of helping prevent these sorts of attacks.
To do a better job of evaluating it, you will need to provide more details on what your requirements are. What are you trying to do? What do you need to integrate with?
edit
Even after your clarification, it's still not exactly clear what you're looking for. Even restricting yourself to expanding a single Mustache template with a single view as input, you can produce any arbitrary string, and thus any arbitrary HTML by just give it that string as input.
If you're asking whether you can perform any arbitrary computation given a template and a view to render, then the answer to that is also yes, because Mustache allows you to call functions in your template, and those functions are written in Javascript, which is Turing complete.
But both of these are trivial answers; you can produce any given output by providing that as input, or you could do any given computation by using a higher-order section. As I said previously, what is possible to do with it is less interesting than what is easy to do with it, and what mistakes are hard to make with it.
I suppose one weakness, that may be the type you're looking for, is that if you need more power than the Mustache system itself provides, you need to pass those functions in as part of the view. Thus, you need to conflate the object that is being displayed with the code that will be used to display it. And if you remove the ability to to call Javascript from the views that are passed into the templates, then you do severely limit what you can do. Given the fact that these objects are known as "views", it seems that it's by design that you mix in the presentation logic with them; this is very different than template systems in which you allow the template to extract values directly from your model objects.
Yes, there are many things you can not do in mustache. Mustache is simpler than some other full-featured template systems ( like the one in Django ). Mustache is a very minimal template system which encourages you to ( through it's lack of features ) to implement "logic-less" templates. This means that some processing that you can do in other template systems must instead be done in code that modifies the data that is sent to the template.
It's not bad template system, it's just a minimal system that aims to be simple and fast.
So, I would say that the answer to this question is: "Yes, there are things you can not do in Mustache ( compared to some other template systems )".

Practical use cases for returning javascript from an XHR/Ajax request?

I've never really had to return javascript from an XHR request. In the times I've needed to apply behaviour to dynamically loaded content I could always do it within my script making the call.
Could someone provide actual real world cases just so I'm aware, of when you'd actually need to do this ( not for convenience ), or some reasons of why in some cases it's better to return js along with the other content instead of building that functionality in your callback?
The only scenario that's coming to my head is on a heavily customized site, if the site supports multiple languages for example and the functionality changes depending on the language, and ajax is used to pull in dynamic content and perhaps in some languages a certain behavior needs to happen while in others another needs to happen and it's more efficient returning js in script blocks instead of dumping all that logic into a callback.
Sometimes it is more convenient to "prepare" the JavaScript code on the server side. You can use the server's programming or scripting language to generate the code and you can fill it with values from the database. This way most of the logic takes place on the server and not the client. But it is really a matter of taste. OK, that wasn't a real world case but maybe my opinion is helpful anyway.
We use XHR to request an entire web page that includes java script for menus etc. We then replace the current page with the new one that has been sent over XHR

Categories