Why is innerHTML = "" slow in Firefox - javascript

I am testing the speed of different methods to dynamically add html elements to the DOM. I've build a tester here (code is working version, so pretty sloppy). The results are (very) different for different browsers with Chrome getting all the points for speed, and Opera a good second - but that's not the question here.
In Firefox I detected a problem with clearing a div (from it's childNodes). When some 50.000 div elements are added, it takes ages to clear, using just
[div].innerHTML = "";
What is going on here? Did firefox implement some intrinsic garbage collection method for this?

While I am not sure about the innerHTML = "" you left out one possibly fast appoach using DocumentFragments for inserting into the DOM: As John Resig shows.
As Ólafur Waage already mentioned, even though innerHTML is faster in a lot of situations since it's not part of any W3C standard, quirks are far more likely to be introduced then if they were. Not to say innerHTML is not a defacto standard within modern browsers.
This blog post seems to indicate that Firefox spends a lot of time cleaning up after itself when using innerHTML to remove elements.
In some browsers (most notably, Firefox), although innerHTML is generally much faster than DOM methods, it spends a disproportionate amount of time clearing out existing elements vs. creating new ones. Knowing this, we can combine the speed of destroying elements by removing their parent using the standard DOM methods with creating new elements using innerHTML.

innerHTML is not a part of the W3C DOM specification.
It should never be used to write parts of a table—W3C DOM methods should be used for that—though it can be used to write an entire table or the contents of a cell.
As there is no public specification for this property, implementations differ widely. For example, when text is entered into a text input, IE will change the value attribute of the input's innerHTML property but Gecko browsers do not.
For those wishing to adhere to standards, here is one set of JavaScript functions offering to serialize or parse XML so as to set element contents defined as string(s) via the DOM or getting element contents obtained from the DOM as a string.
Source - Mozilla Dev

Related

When do browsers reject invalid html? Especially when dynamically created

Modern browsers routinely fix invalid html by rearranging elements in the DOM, but when you create the same html-structure with JavaScript, it remains intact. Why? This seems consistent across browsers. Is there a W3C recommendation how such cases should be handled? Under what circumstances can we expect browsers to intervene?
For examples, see the following JSFiddle: https://jsfiddle.net/od0uwxsb/
It includes span-Elements in place of td-Elements and table-Elements inside p-nodes. In both cases browsers fix the invalid html in the initial load, but keep it intact when the structure is created dynamically.

Selecting a DOM element using javascript document.myElementsName

I'm working on a website which was coded a while ago.
I've found a Javascript function that uses the following syntax to set a value for a text box
document.myForm.myText.value = "value";
I've tested this code and it works in IE, Firefox and Chrome.
My question is whether this way of setting/selecting DOM elements is ok going forward (ie. is it going to get depreciated)? Should I change instances of this type of element selecting to the more standard (in my experience) code below?
document.getElementById("myText").value = "value";
Thanks in advance.
I don't think it'll make a difference cause the browsers dom representation will have change to break the code; That'll probably break half the web pages on the internet.
Your code is better than the first because you will then be coding to the contract of the method getElementById, which returns the HTMLElement you need. This means that the JS Engine has to adhere to the standards of ECMAScript and return the exact element. Hence your code doesn't need to worry if tomorrow a browser changes it's structure and your element is now document.forms.myForm.myText.value instead of what you anticipated.

AppendChild issue with Internet Explorer Javascript

The following piece of code, works correctly in Firefox and Chrome, but it gives me a headache in IE.
var anotherDiv= document.getElementById("anotherDiv");
var destination = document.getElementById("mySourceDiv");
destination.appendChild(anotherDiv);
I'm trying to get a Div element and place it inside another div.
I get an error message (in the debug console in IE) similar to "interface not supported", and points me to the appendChild line.
What I've seen is that the type of the destination variable is an object rather then a DOM element.
What can I do to append the anotherDiv to mySourceDiv?
I'm trying this in IE 8.
You probably will need something like an importNode, there are various cross browser solutions around. The issue is that each node has a corresponding document object on it, in IE and so called security doesn't play nice moving things from one document to another.
So, essentially it's doing a deep clone, but the difference between using cloneNode is that cloneNode also sets the document which you don't want.
This might get you going in the right direction:
IE support for DOM importNode
I'd recommend using a library designed to sort through the browser incompatibilities for you. I've personally found jQuery to be quite good. jQuery has an append function.

Most efficient way to use selectors in jQuery?

is it more efficient to use $('.active') or $('div.active') ? I have always avoided including "div" because it's extra text in the javascript file I don't want the user to have to download.
Older versions of IE will benefit from the inclusion of div because they don't support getElementsByClassName().
Because of that, every element on the page needs to be selected with:
document.getElementsByTagName('*');
...and manually tested to see if it has the active class.
If you include div, then it is able to narrow it down a bit, since it can do:
document.getElementsByTagName('div');
...then test only those elements.
When I say older versions, I mean IE6 and IE7 since IE8+ supports querySelectorAll.
EDIT:
Browser suppport:
getElementsByClassName: http://www.quirksmode.org/dom/w3c_core.html#t11
querySelectorAll: http://www.quirksmode.org/dom/w3c_core.html#t13
It depends. If you mean performance.
I prepared special test for everyone on JSPerf: jquery class selector test.
On my browser and computer (FF 3.6.13 and Core 2 Duo 1.6) div.active is a bit slower. But found it variable - it seems GC has something doing here.
And after few more tests it seems that div.active:
Speed is variable on FF, sometimes GC turns on 'div.active' test, but generally difference is very small.
Unnoticable difference on Chrome and Safari
Faster on IE9
I like to include the tag name if it helps self-document the code. If I can use
$("nav.primary")
instead of
// this is the primary nav
$(".primary")
I tend to do it.
I guess the best way to get some speed on large pages is to use find instead.
$( your-container ).find("div.active")
Since you always? know where you should look, you can create your own scope. So that the browser only need to search within that area of code.
By the way, you don't need to care about size of the css, EVER :)
Use css minifing tools to minimize the css when the site is in production mode. You can also set your web server to automatically gzip your css files before sending the to the user. And if you don't change your css filename on every pageload, the browser cache up to whole css file.
CSS selectors in jQuery used to be optimized similar to how you would do it for browsers, see: http://css-tricks.com/efficiently-rendering-css/
Specifying a generic tag anywhere, even with an ID or class would be dramatically slower than just specifying the ID or class alone. See:
http://www.no-margin-for-errors.com/demos/how-to-optimize-jquery-selectors/
The above uses jQuery 1.3. Since jQuery 1.4 and the introduction of the Sizzling selector engine, this is less important from what I understand. See:
http://hungred.com/useful-information/jquery-optimization-tips-and-tricks/
For myself, I decided in CSS to use whatever reads the easiest, and I am more specific there since that is only parsed once. In jQuery, however, I have been more careful since those selectors could run thousands of times over the life of a page.

reliable, cross-browser way to get selection's boundaries?

I need to make the user to be able to select some text, click a button and make the server remember the selection for the next time.
I've extensively read through SO's questions and answers, tried some libraries, but without luck: haven't found a reliable tool yet.
It isn't important how the selection's boundaries are identified: it could be "nth textNode, mth char", or "nth char of text", or "nth char of html", or whatever, as long as it allows the server to identify the points in the document; what really matter is that, selecting the same words of the same document must give the same result on chrome, safari, IE, firefox.
EDIT: I don't need it to work everywhere on the internet: just on one site, where the document's structure is fixed and only the content of a single div (or the like) will change.
Try my Rangy library and its Serializer module. I'm not convinced it's exactly what you want because you mentioned the server remembering the selection, whereas my suggestion uses cookies, and the serialized selection will vary between browsers. However, it does do as you described in the first paragraph.
On the other hand, it's pretty much impossible to write something that will work for all browsers and all pages, since browsers interpret HTML differently and build different DOMs.

Categories

Resources