What is the best way to include data in an HTML page? - javascript

What is the best way to include data in an HTML page? The data is not human-readable and will be processed by a script once the page has loaded. The options I can think of are:
Using class and title attributes on hidden/empty <div> or <span> elements within the page
JSON in a <script> element at the bottom of the page
Load the data via an XMLHttpRequest after the page has loaded
XML Data Islands
All of these methods seem to come with drawbacks so I would like to know what your thoughts are.

I would use JSON in a <script> element. Actually, I would make it an actual script. The browser is going to parse and evaluate the JSON, so take the opportunity to store it in some variable.
Hiding elements using CSS is kind of fragile, as some clients (not necessarily browsers, think search engines) may still see them as part of the page data.
Loading the data through XHR after page load is fine, but it's not strictly an answer to the question. Its also a bit slower as it incurs an additional server round-trip (think of your antipodean users, low latency is very important to them).
XML Data Islands: I am not sure what you are referring to, but it sound like something that would cause much validator complaints, and which might be fragile in that string node could be rendered by the browser.
So, storing the data in a <script> element sounds like the simplest, safest, most appropriate way to answer the question.

I'd go with JSON. Or some other JavaScript code if there is reason for it. That will be easiest for the script to consume, and it is limited only to what the script itself is limited to.

Related

Correct deployment of structured data for Google rich cards

I am confused as to the correct inclusion of structured data, primarily for google rich media.
1. Must/should every page have it's own json, or should the root page contain the json for all pages?
2. The structured data is essentially JavaScript. Does it have to be inline, or can it be in another file?
3. A normal browser might waste time with big structured data JavaScript - information which is irrelevant to it. Is there a good solution/best practice for dealing with this?
Yes, it should. Structured data is based on the URI paradigm. It means, the unique ID of the document is its URL. So yes, your structured data belongs always to certain URL.
No, it isn't. JSON-LD is not a javascript, even thought it is implemented with the <script> - but it isn't a javascript. And no, it can't be in another file.
Not, it doesn't. Browser don't interpret JSON-LD scripts - they don't need it, this information is not for them and it isn't relevant for the browser's job, which is page rendering. JSON-LD scripts can indeed be placed on the bottom of the HTML source code - but you will not realize any acceleration impact by this.

AJAX - Sending html-fragments ok?

I want to create a website where the user enters data in a formular and a php-script uses this data to create html-code which shall be inserted in a div-element. Using AJAX seems to be the right way to do this, but there is one thing that bothers me. in my opinion a script should always generate a whole document (doctypt-declaration, head, body etc.), but if i use AJAX i have to send only a fragment of a whole document, because i would have to write something like this:
document.getElementById("mydiv").innerHTML = ajaxObject.responseText;
So i would like my PHP-script to send a whole document, but i cannot assign a whole document to the inner html of an element. is there a way that javascript can process a whole document, and insert the documents body in a div or should i maybe use iframes instead?
in my opinion a script should always generate a whole document
A big no to that! Have a look on other data formats such as json which is widely spread, or xml. Some formats do not even follow certain document structures that say: here my document starts, title belongs here, that must be like that, the other thing has to be like this and here the document ends. There's just bare data (of course under the accordance of the syntax).
The server doesn't need to return HTML at all (if you don't want it to). The opposite is the case. Provide as many output formats as you can.
Think of other client applications that would use your script, such as non-js applications or applications outside the browser that can't even handle HTML.
Would you always write a new script or change your existing whenever you need another output data format, or would you rather have a strong serverside application structure that can handle the output of several data formats?
Think of your server as an interface. It returns the data that you request. How you handle the data is absolutely up to the client (the server should not even care) in this case.
Also returning HTML chunks is absolutely okay in your case. That's what I would do here too.
What I want to point out is that you absolutely don't need your script to return a whole HTML document (isn't exactely that even a big advantage that came up with AJAX?)
If you don't mind using a bit of jQuery,
$('html').html(ajaxObject.responseText);
If you just want change whatever's in the body,
$('body').html(ajaxObject.responseText);
As suggested in the comment below, it without using jQuery,
document.body.innerHTML = ajaxObject.responseText;

create html elements on the serverside VS get data as JSON and create tags with javascript

I want to create a AJAX search to find and list topics in a forum (just topic link and subject).
The question is: Which one of the methods is better and faster?
GET threads list as a JSON string and convert it to an object, then loop over items and create a <li/> or <tr>, write data (link, subject) and append it to threads list. (jQuery Powered)
GET threads list which it wrapped in HTML tags and print it (or use innerHTML and $(e).html())
Thanks...
I prefer the second method.
I figure server-side you have to either convert your data to JSON or html format so why not go directly to the one the browser understands and avoid having to reprocess it client-side. Also you can easily adapt the second method to degrade gracefully for users who have disabled JavaScript (such that they still see the results via standard non-JS links.)
I'm not sure which way is better (I assume the second method is better as it would seem to touch the data less) but a definitive way to found out is try both ways and measure which one does better.
'Faster' is probably the second method.
'Better' is probably subjective.
For example, I've been in situations (as a front end dev) where I couldn't alter the html the server was returning and i wished they would have just delivered a json object so i could design the page how i wanted.
Also, (perhaps not specific to your use case), serving up all the html on initial page load could increase the page size and load time.
Server generated HTML is certainly faster if the javascript takes long time to process the JSON and populate the html.
However, for maintainability, JS is better. You can change HTML generation just by changing JS, not having to update server side code, making a delta release etc etc.
Best is to measure how slow it really is. Sometimes we think it is slow, but then you try it out in real world and you don't really see a big difference. You might have the major delay in transmitting the JSON object. That delay will still be there and infact increase if you send an html representation from the server.
So, if you bottleneck really is parsing JSON and generating html, not the transmission from server, then sending html from server makes sense.
However, you can do a lot of optimization in producing the html and parsing JSON. There are so many tricks to make that faster. Best if you show me the code and I can help you make a fast JS based implementation or can tell you to do it on the server.

Passing data between elements in UI

I'm new to web applications and am trying to understand the best way to work with data in HTML. I'm using Appengine (Python) and have managed to load a bunch of data to the view. In the simplest form, it's a set of movie names and each name has associated details with it (e.g. year, rating etc). Now how do I pass data between the movie link and then a div where all the details will be displayed? I'll be using jQuery for some controls in my application so I'm wondering if there's a way to do data binding to controls with that?
Additionally, can anyone tell me what're the standards around this i.e. if I load all this data to the UI in one call (assuming it's not a lot of movie titles), wouldn't it make it easy for people to screen scrape this information? Or is there some obfuscation that's typically used here?
Sorry if I'm not very clear but I really am an absolute beginner with web development!
Update1:
I found the jQuery data() api. It seems like this'll work. Comments?
Update2:
Some testing later and it turns out that data() actually attaches the data to the elements rather than showing it in a div itself.
There's a few ways to do it but the basic idea is to put the data in the HTML in a way that is not visibly rendered, then use Javascript to parse the HTML and pull the data out when you need it.
The easiest way on modern browsers is to use data- attributes. These are any attribute that start with data-, and you can name the rest yourself. For example:
Czar Wars
In this case, the user will only see a link called "Tsar Wars" but your javascript can easily access the data- attributes to get the data it needs. The other benefit of this approach is that jQuery will automatically make data- attributes accessible by the data() api.
Another way to do it is to have a hidden HTML list element with all your data elements in the list, but you'll have to parse this all yourself.
There's no standard obfuscation. You'll need to obfuscate yourself on the server side, and unobfuscate in your JS. It's not too difficult to figure out any obfuscation algorighm in js, so this is not worth your while.
If the data really is private, then you would have to architect it as to do all the processing on the server. For example, only show tokens (like 1234), and use AJAX calls to pass the token to the server so the server can do the data processing and spit back publicly safe results to the script.

Optimal way to pass system values to javascript

What is the most effective way to pass object and category ids or other system variables which shouldn't be presented to the user, from server to the browser?
Let's say I have a list of items where I can do something with each of them by javascript, for example show tooltip html or add to favorites by ajax, or display on a map. Where is it best to save that tooltip html, or database id, or geoposition?
Some options I can think of are:
some dictionary within <script></script> tag for each item,
microformats,
inline xml,
rel attributes,
css class names with specific information, e.g. class="lat-12345 uid-45678",
one <script></script> with a dictionary of html ids mapping dictionaries with system values in the template,
javascript generated from the database and included via <script src="..."></script> with a dictionary of html ids mapping dictionaries with system values in the template,
ajax requests for all cases when I need more information than just id,
event handlers with parameters within html tags, e.g. onmouseover="tooltip(this, 123, 'Hello world!')".
P.S. I prefer unobtrusive solutions and also the loading/execution time is important.
Perhaps I am missing something... why not just JSON?
How you "send" it (either in the initial page load as "javascript" or via AJAX or whatnot) is really just a trivial detail determined mostly by when the data is available. (JSON is a subset of legal JavaScript syntax.)
Then it's just a matter of the correct transformation. Of course, by pushing this to JSON/JS, you may render some non-JS clients non-interoperable, if that's a consideration for you. If such is indeed the case, why not just perform the transformation server-side using well, any number of the techniques you put at top?
You can also use arbitrary attributes in HTML (the HTML5 spec may include "data-*" which is formally legalized) -- while not technically "correct", all major web-browsers will accept unknown attributes which can be accessed through the DOM API.
I'd prefer a single AJAX call to fetch whatever data you know you need at the outset, so you can have a simple JSON object available in your script. You can, of course, supplement that with additional calls should you find you need more information.
If that's impractical, then "hardcoding" a JavaScript object in a <script>...</script> tag is the next best option. Of course, "hardcoding" is from the browser's perspective. The actual content would surely be written by server-side script from your database.
One method you can use is custom attributes. I think you refer to this as micro-formats, but I am not entirely sure if they are the same thing so I have written a description below.
Having hit the same question before, I basically use something like the following:
<div data-pid="1234">
<a href="#" class="add-to-favourites">
<img src="addToFavourites.png" />
</a>
</div>
$("a.add-to-favourites").click(function() {
$.load("/Favourites/Add.php?prodID="+$(this).parent().attr("data-pid"));
});
This should do exactly what you want to do. The reason I have put the pid in the div, not the a tag, is that you can then place all the other product information within the div with other actions the user can take, for example displaying a tooltip on mouseover using data-description, or displaying on a map using data-geo-x and data-geo-y. Of course you can name these anything you want.
Support / Acceptance
This is becoming a perfectly accepted way to do what you want to do. HTML 5 supports this for precisely the kind of thing you are trying to achieve.
So it is supported by HTML 5, but what about HTML 4?
It may make HTML 4 invalid, but the world is moving on to bigger and better things. Older browsers (IE6 and before, FF1 / 2, Opera 7 / 8 / 9) are becoming less common so it shouldnt be a problem. It wont actually break older browsers - the functionality will still work.
Important validity note
Make sure you prepend the data- onto the attribute name. This will make the attribute perfectly valid in HTML 5.
A few extra hints
In jQuery 1.5, I have heard from an answer to my question that you can simply specify attr("pid") to return the value of data-pid. If this is the case then I would be careful when naming the second part of the attribute name after the name of an actual attribute (for example, instead of data-id, use data-pid - especially if the id attribute is specified. I am not sure what effect it would have if you didn't do this, but its better to avoid the problem in the first place than have issues with the site at a later date due to this.
Hope this is what you were looking for.
ASP.NET offers a very convenient way to do this. You can simply write a JavaScript object. I am sure other templating engines offer similar ways to do this.
var person = {
Name : <%= _person.Name %>,
Age : <%= _person.Age %>
};
I would implement a Javascript singleton AppCacheManager that initializes in the document.ready event. A bit JS oop and you have a fully fledged OOP datastore.
Whenever information is needed, you load it through Ajax / RESTful Webservice and cache it in the AppCache Manager. So you have 2 caches: 1. Browser Cache, possible due to RESTful webservice URL caching, and 2: the JS Cache Manager.
You access all requests to the AppCacheManager which transparently fetches the new data or returns the cached data, so that the client doesnt need to know anything of the caching.
in short:
write a JS CacheManager
don't fetch the whole data at once but in small parts when needed and cache them
define a convenient interface for the cachemanager
Example usage:
linktext
Unobtrusiveness is a very difficult thing in JS and i'd be eager to know something about that, too.
hope that helped.

Categories