How do I prevent unnecessary resource-load when I create new HTML elements? - html

Update:
Finally, I guess I was asking a stupid question. The jQuery creates DOM elements and it will be requested anyway. So I think it's better to use .html(xxx) to implement the feature rather than using $() to create anything before.
This is quite tricky and I never realize it before. But today I realized it's very important to a web project.
Say I have two images created dynamically:
var $img1 = $('<img>');
$img1.attr('src', 'http://domain.com/1.png');
var $img2 = $('<img>');
$img2.attr('src', 'http://domain.com/2.png');
Right after the browser runs the code above, the two images would be requested. That would be a waste of the client's and the server-side traffic.
Is it possible for me to control when the resource request be sent?
My expectation is NOT to do it by assigning src later because in my case it'd be much more complicated, the HTML code is containing a lot of stuff rather than some img tags. For example, is it possible to tell the browser that "please wait until the img tag is added onto the DOM tree"?

Append the images to DOM after the page load like this:
$(document).ready(function() {
// You could use whatever jQuery selector here you like to
// determine where to append the new elements.
// For this example, I am just appending to end of document.
$(document).append($('<img src="http://domain.com/1.png>');
$(document).append($('<img src="http://domain.com/2.png>');
});

Related

Is it possible to nest one data: URI inside another?

If I use a data URI to construct a src attribute for an HTML element, can it in turn have another data URI inside it?
I know you can't use data uri's for iframes (I'm actually trying to construct an OSDX document and pass it to the browser with an icon encoded in base64 but that's a really niche use case and this is more of a general question), but assuming you could, my use case would look like:
var iframe = document.createElement('iframe');
var icon = document.createElement('image');
var iSrc = 'data:image/png;base64,/*[REALLY LONG STRING]*/';
iframe.src='data:text/html,<html><body><image src="'+iSrc+'" /></body</html>
document.body.appendChild(iframe);
Basically what I'm after is is there anything in a data uri that would break a parent data uri?
Yes you can. I really thought it was impossible, as did everyone I asked.
Example:
Pasting the following into your browser's URL bar should render a gmail logo in an html page that says hello world.
data:text/html,<html><body><p>hello world</p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAsCAMAAAApWqozAAAAz1BMVEX///+6xs7iTULj5+vW2tzk49TX3+Tq6tz09Orz9/jm7O6wu8aNm6WwMCjfRDnm5ube2Mmos7vt7++jrLP29/eyTk3d4+fj6+foWFLM1t2bNzeZpa2trKPv8/ajo6Xud2f0r6rv7uG3ubvd6eXIysq9s6jeopfSUknx8fHbXGKvTx7Hz9X09PTwhXHw9Pb++/fp7/Xu4d3SZlPSiXjuaFmMkZX39/vZy6/j8+v2+/v76uP7+/v0/Pewl4raMi/f5+7KTjitf4W2rI3/9vDzz8uC91bdAAAAAXRSTlMAQObYZgAAAmBJREFUeF6VldeunDAQQNeF3jvbe729p/f//6aMxzaBKHe5OZiVJY6OBvbBAyTvZaDJSy/xzpJ4pdJzz1tfOme5LD0vly45fETe4/1vUoK26bnPznUPzrPrmSJsgtrPpQnpPCmvp2/gukyE/HX6JtYor9/kpqUcY3ogvUxv5RhlSrbHenFzY/+0cxtYApZlGZod3W9JaqJspuSR1vTqw41U4UZb+S/zMAz35FbJt4QK6sUnW+naxWwoaJXBpBi37bxTjuchyl+0zLGs4npmVK1dHSLBiLhmlg+chLukFiLqV3dQ1i84p1SEv42CgLhYzmR5vqh1XIUXeypGoN+LAMoVz5yBk/EKZfsOQioOsnGFWXr/eXLCMs9EeehK2bab+NKCbQj2/mEymRSjpqzkR5CXOv4AWSqyM3BnRSDKw255CWtBW0BWcILyCmQsMywv5b/xS8WpzGJZzMywPFZjvANTYO10VoNfIxqOW2WlwhU/QnbSMDu1y0yWpSowdiqry6OArEW5ka1GNTaGsWqViwDL4z/lezClu4nBN+K/ypWSIywrNY4NxaqZWZSjThlEkQXLUna8lTZ+unWnDE6T1fbmtZlBxWxbFvHZ5NR8DUeUj5QejQ1mu24cv2C5aJW3R3qv1a4bX8TbIih+wAv6IPvDKCIrAusV8FEpyz5njFUV/ERdWFTBHVWwmGkyKKPcT2kyjvKFy1jPgnJ6IeTMg30vzCUZHBTc52mvzdKhz+GYcJIxTw8ukOKlVmd/SPk4kSdQ4nv8fJh7PriIw7Mn/yxPGW8dm06e269eOTwe/De/AW24fWb7B21TAAAAAElFTkSuQmCC" /></body></html>
or for a shorter example courtesy of Pumbaa80:
data:text/html,<script src="data:text/javascript,alert('hello world')"></script>
MSDN explicitly supports this:
Data URIs can be nested.
An old blog entry talks a little bit more about embedding images within CSS using data: :
Neither dataURI spec nor any other mentions if dataURI’es can not be nested. So here’s the testcase where dataURI’ed CSS has dataURI’ed image embedded. IE8b1, Firefox3 and Safari applied the stylesheet and showed the image, Opera9.50 (build 9613) applies the stylesheet but doesn’t show the embedded image! So it seems that Opera9 doesn’t expect to get anything embedded inside of an already embedded resource! :D
But funny thing, as IE8b1 supports expressions and also supports nested data URI’es, it has the same potential security flaw as Firefox does (as described in the section above). See the testcase — embedded CSS has the following code: body { background: expression(a()); } which calls function a() defined in the javascript of the main page, and this function is called every time the expression is reevaluated. Though IE8b1 has limited expressions support (which is going to be explained in a separate post) you can’t use any code as the expression value, but you can only call already defined functions or use direct string values. So in order to exploit this feature we need to have a ready javascript function already located on the page and then we can just call it from the expression embedded in the stylesheet. That’s not very trivial obviously, but if you have a website that allows people to specify their own stylesheets and you want to be on the safe side, you have to either make sure you don’t have a javascript function that can cause any potential harm or filter expressions from people’s stylesheets.

Hide values from page source but show on page

I would like to be able to show some values on the page but hide them in the page source. Im pretty sure this is not possible, but i figured i would ask.
Edit
I am writing my own verification system to prevent hackers/spammers. Im using encryption when passing the data, but the original value can be currently viewed in the page source ( thus someone can write a loop on the source and pull the data ).
Officially as per your tags not including javascript: No...
However, it's possible to write to the DOM after load but probably not going to achieve what you want in the end.
You can do something like this:
<div id="something">
</div>
Then on page load use javascript in your footer to inject the value of that div:
<script type="text/javascript">
document.getElementById("something").innerHTML = "This is a previously hidden value";
</script>
This will write it to the dom after load and not write it to the page source. The real question is what are you actually trying to do? If you want to totally hide something then this is pretty much just an inconvenience. Anyone wanting to drill it out will be able to track this down.
If you update your question with your real intentions then maybe we can offer a better solution.
EDIT
As per your edit that you want a validation system that does not display the original values.
One option is to store the values in a database and only pass the reference id of the row to the form, assuming that's what you mean. You can do all your processing on the server side and minimize the amount of sensitive data passed to the client side.
The immediate answer is no, this is not possible -- because the browser must receive anything it intends to display.
With that said, depending on your intentions there are ways to display content to the page but hide it in the source.
One common place where this is an issue is with emails that you wish to hide from spambots, but need to display to your user -- if this (or something similar) is the case, I present a couple of solutions:
Use HTML character entities to obscure words: See here.
Use Javascript to dynamically generate it
Use HTML encoding: Here is a nice tool.
Use a plugin such as SilverLight with DRM: See Here.
Serve an image (note, some spambots know how to use OCR)
Use something like reCaptcha mailhide
At the end of the day, the user will almost definitely be able to copy whatever it is you are trying to hide - but if you are only trying to defend against spambots or automated tools, one of these options might work for you.
The way to do this is to have a <div id='fillme'> (or some other container) on your page, and then use AJAX to populate it with information after the page loads. That way, when someone clicks on "View Source" they'll see the contents of the html (or php or whatever) file that was loaded, rather than the end result after the javascript runs. jQuery has wonderful AJAX functionality, and you'll end up with code like this:
$.ajax({
type: 'POST',
url: '/server/side/script.php',
dataType: 'json',
data: { thing: value, thing2: value },
async: false,
success: function(data) {
$('#fillme').html(data);
},
error: function() {
alert('oops');
}
});
Since the page source is all the data a browser needs to generate everything on the page, it isn't possible no.
Ofcourse you could show images instead of values, isn't directly readable from the source code. Or use a html5 canvas or something.
Unfortunately, the short answer to this question is, you can't. There have been various methods put forth, but all of these are easily circumvented. In the end, the only sure fire way to make sure no one can steal your source code is to never put it on the Internet at all.

Getting started styling JSON search results from DocumentCloud

I'm looking to build a system that styles the search results from DocumentCloud (and allows me to link to a given document).
I know I can query DocumentCloud and return JSON results using a search string like this:
https://www.documentcloud.org/api/search.json?q=obama
I don't know how to:
Grab the output of the search and put it on my own page
Style the data once I have it on my page
I'd just like to know how to get started with this, I'm experienced with HTML and CSS but I've never worked with JSON before.
There's more info here but I just don't know where to get started: https://www.documentcloud.org/help/api
It sounds like you're not so familiar with JavaScript, correct? JSON stands for JavaScript Ojbect Notation, so to work with it, you'll have to dive in a bit. I strongly recommend looking into using a JavaScript framework/library, namely jQuery to handle the heavy lifting. (There are other worthy libraries, but jQuery is by far the most popular, and is very friendly, using CSS-like selectors to manipulate the document object model).
check this jQuery tutorial: How jQuery Works
Here's a primer on using jQuery's jsonp to fetch remote rsults and using them in a page: http://www.ibm.com/developerworks/library/wa-aj-jsonp1/
You might end up with code in a javascript file, or a script tag (following a link to the jQuery library) that looks like this:
$(document).ready(function () {
$.getJSON('https://www.documentcloud.org/api/search.json?q=obama&callback=?', null, function (results) {
// this would append whatever the json returns for 'total'
// inside an element on your page with an id of 'resultsCount':
$('#restulsCount').append(data.total);
});
});
As a result, extra text & markup can be added to elements you already have on your page in whatever form/position you need it, and regular CSS rules from any style block or CSS file linked on your page will apply to them.
Good luck.

Are there any solutions to make my ajax script stable regardless of HTML changing?

I'm running a content-based website, and I usually used ajax to dynamically add items to the content list. Every time I updated my item structure I have to change my javascript to fit the new structure. I wonder whether there was any solution to keep script stable regardless of the changing of HTML?
Simple, instead of using the DOM to handle your data, process everything upon completion of the ajax request and only then call a function that has all of your data display functionality. Obviously you can't get away from having to change some code somewhere when you for instance rename HTML elements but you can separate concerns so that you only have to touch code in one place.
I do quite a bit of this in my app, and I follow the same pattern every time:
View page fires an ajax function to another page, which I call the "dispatcher" I use this pattern because I want a plain text output without header, footer, other JS, etc, so the dispatcher is a simple page that gets the request from the Ajax, fires appropriate PHP functions, and echos the results. In some cases it will return JSON strings while in others it will return HTML or plain text. For your example, return HTML from your server-side language.
Back in the AJAX success callback, inner html (.html()) an element with the returned html content. Have your server side language do the work of assembling the HTML (or even text if you're so inclined) because it is far less work and less overhead to accomplish.
Not too bad, huh?

How do web browsers implement a text search?

I would like to build an application that contains HTML web control, and enables searching and highlighting multiple phrases in the html area, like it's implemented in web browsers today.
The main idea is to make the search ignore the html special tags, and refer only to the real text (the inner html).
I know that the solution will include editing the DOM, but I'm not sure how this could be implemented.
I searched a lot over the net, and I read also the post of Zavael, but unfortunately I couldn't find any suitable answer. Any answer, example or direction will be appreciated.
If you are referring to an inline search of HTML content within the page: firstly I would say that it probably isn't a good idea. You shouldn't supplant the browser's native functionality. Let users do things the way they are used to. Keep the experience consistent across different websites.
However, if you need this for some niche purpose I don't think it would be that hard.
jQuery could achieve it. Just a very rough start:
//As you type in the search box...
$("#search_box").change(function() {
//...you search the searchable area (maybe use some regex here)
$("#search_area").html();
});
EDIT: Questioner asked if I can elaborate on the code.
//As you type in the search box...
$("#search_box").change(function() {
//This part of the code is called when the contents of the search box changes
//This is the contents of the searchable area:
$("#search_area").html();
//This is the contents of the search box:
$(this).val();
//So you could perform a function here, like replacing the occurences of the
//search text with a span (you could use CSS to highlight the span with a
//background colour:
var html_contents = $("#search_area").html();
var search_tem = $(this).val();
$("#search_area").html(html_contents.replace(search_term, '<span class="highlight">'+search_term+'</span>'));
});
Please note that in the above example, the Javascript 'replace' function will only replace the first occurence. You need to use a regular expression in the first paramater to replace all. But I don't want to write all the code for you ;)