Is this method of creating html elements in JavaScript considered outdated? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
In the newer versions of JavaScript, I know that you have to createElement() then you have to appendChild() if you wanted to create and html element in JavaScript. However, I stumbled across this method of creating html elements using Jquery and I was wondering if it was outdated?
$("#options").html("<option value='Millimetre'>Millimetre</option>")
Thanks for any answers!

It's not that it's outdated, it's that this syntax depends on the jQuery library, and jQuery is still concerned with imperative DOM manipulation. These days, most UI frameworks use declarative patterns because they are easier for developers to author and reason about. Declarative patterns move the complexity closer to the level we can handle, rather than requiring us to move our brains closer to the complexity of the mutation logic.
But we can strip out the jQuery and do basically the same thing:
create a string that contains HTML markup
inject that string into the document using .innerHTML
There are reasons folks don't like working with strings of HTML, which is sometimes called "tag soup":
there's nothing to protect against basic typos or markup mistakes like nesting errors
tag soup is hard to read, because even in an editor with intelligent syntax highlighting, the tag soup is just a string, so it will all be one color
some characters which are valid in HTML need to be escaped inside tag soup, which makes it even harder to read
long strings of tag soup typically make for very long lines of code; very long lines of code are hard for humans to read, and do not diff well; there are patterns for mitigating this, but that's an extra hassle you have to deal with
That said, there is one really big benefit that tag soup has: better runtime performance. DOM manipulation is typically one of the slowest things javascript does within the browser. I haven't run tests recently, but back in the day a single DOM operation usually took about 100ms. That maybe seems fast, but if you're adding hundreds or thousands of nodes to the document it can add up to several seconds. Setting innerHTML is also a DOM operation, but that one operation can create, modify, or remove hundreds or thousands of elements at once. Yes, an innerHTML op that adds thousands of elements will probably be slower than an innerHTML operation that only adds 5 elements, but it'll probably still be at least one order of magnitude faster than adding each of those elements using individual operations.
Worry less about whether the thing you're doing is "cool" or "cutting-edge." Focus on whether you're using the right tool for the job, whether the tool makes your job easier or harder, whether the tool is reliable across all the platforms and timespans you care about.
It's not your job to please the cool kids. It's your job to write software that does the right thing, for the right reasons, in the most obvious way possible.

Pretty much everything regarding Jquery is consider outdated, that's why sites such as Github and frameworks as Bootstrap are droping Jquery use.
The non outdated will be in fact handling the DOM yourself whit createElement() (which Jquery does under the hood), but as you can tell it gets pretty complicated doing all that yourself
So alternatives are:
using a web front end framework such as Angular, React or Vue
using a modern library to handle DOM updates
Not saying Jquery is useless it still gets the job done but there are many reasons not tu use anymore, most of them comming from the fact that JS got many new feature that are now native and not having any need to re implementing with more code from Jquery

Related

Changing content by manipulating the DOM w. Javascript vs. creating new HTML/CSS pages: which is more efficient? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm building a very simple website with a few different sections like "about us", "pictures" and "contact".
I'd like to know which is more efficient (better performance and lower response time):
1.Using Javascript to manipulate the DOM and change the contents of the main section whenever the client clicks one of those item in the menu ("about us", "contact" etc) or...
2.Creating a new page (different HTML and CSS files) for each of these 4 or 5 sections I want the site to have?
Thanks in advance!
For decisions such as this is why front-end frameworks like Google Polymer, AngularJs, React, etc were created.
Obviously having a page change (as suggested in 2.) will be much slower than 1, since:
The entire page has to reload (dom is cleared, then re-constructed)
All shared styles/bindings have to be reapplied
Overhead of making duplicate requests (which introduces network latency to page load)
However, though 1 may seem like an appealing design choice, performing un-optimized dom-manipulations (via jQuery) may actually hurt performance even more, since you'd introduce a ton of thrashing, and unnecessary middle steps.
Frameworks like React, handle this by using this by simulating a virtual DOM where:
All operations are calculated in memory
Changes are then optimized
Only the diff of the changes is applied to the actual DOM
Modern web-component Frameworks (like Polymer, x-tag) handle this by using declarative html syntax to bind data to HTML/JS behavior. The optimizations work by:
Leverage shadow dom's which perform operations and styles only to the scope of that element
Statically binding all events to elements created (no need for repetitive even callbacks)
Static referencing to all Id' elements in the component
This results in O(1) selection speed vs jQuery's O(n) approach
Write once, use/customize everywhere approach
As response time and performance are your main priorities. DOM manipulation will better suit your needs by allowing you to implement smooth transitions without a full page load.
As suggested above, you might benefit from using a framework that utilises virtual DOM. In which case, as your requirements are quit simple, a small component-based UI library like riotjs might suffice.
It might also be worth having a look at a single page website with sections that can be scrolled to manually or using a top nav. This would certainly meet your two main priorities.

organising HTML class names and IDs used for different purposes (appearance, jQuery and Selenium) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
There are countless articles on writing clean HTML/CSS.
What I haven't found though is advice on organising class names and IDs that are used for different purposes (design vs jQuery vs Selenium testing).
For any given class name and ID, it's difficult to tell what it's being used for. In 2+ person teams, there also seems to be a tendency to keep adding more and more IDs and classes, and avoiding cleaning up those that are already there, in fear of breaking things.
Are there patterns, conventions, tools, or pearls of wisdom that would help?
I have not come across any tools to help with this situation. But I have used the conventions below with moderate success. None of them are an exact science though.
Regarding IDs:
Because IDs are the faster lookup, I tend to use them whenever I'm wanting to address a specific part of my HTML, regardless of how I'm using it (styling/jQuery/testing/etc).
However, because each element can only have a single ID, there's not really an opportunity to use a naming convention or style for different uses. And I have found that if I've wanted to address an element for one reason, there's a good chance I'll want it again for a different reason.
For example: if I have a button on a page and find it using jQuery (by ID) to attach an event handler, then chances are I'll also want to find that button to test its behaviour.
So because an ID can be used for multiple reasons, it should be named in a general way, ideally describing what the element is or represents, rather than how it will be used. It should then make sense however it is used.
But as you say, for a given ID
it's difficult to tell what it's being used for
I agree, and generally don't try to find out unless I have to. Other team members can't add additional IDs to an element that already has one, and should be encouraged to re-use an existing ID if it fits their purpose.
Using this approach, existing IDs should not be updated or removed, and become a permanent feature of the HTML. (But like any rule, it can be broken if need be and the risk is worth it)
This way everyone should be comfortable to reuse existing IDs without having their code being broken by someone else changing them, and the ID names should make sense for all uses. This should lead to not having too many "extra" IDs.
Regarding Classes:
In 2+ person teams, there also seems to be a tendency to keep adding more and more ... and avoiding cleaning up those that are already there, in fear of breaking things.
My experiences match yours; people tend to add a new class rather than reuse an existing one. This can also sometimes lead to developers being more comfortable to remove a class if they think they've deleted the only code that used it. This in turn bites anyone who did reuse the class, and they think "next time I'll just add my own new class to be safe". A good example of a vicious cycle.
I try to treat classes in the same way as IDs (described above) and:
Use non-use-specific names
Reuse an existing class if there's one already there that "makes sense" by its name
Discourage changing or removing existing classes (to increase confidence with reuse)
With additional thought, an exception could be made for classes added for only "external" reasons, such as testing, by having classes with a common prefix such as "tst". I would consider this approach if the use:
Will create a large number of classes (noise)
Is expected to be changed a lot (as the usage is bedded down)
Expected to possibly be replaced in future with a difference approach
Is controlled by an external group to the development team
But using any kind of naming convention is only as good as the people who follow it (or don't). Testing is really the only way to know if something has been broken when there isn't a compiler to tell you that there's a bad reference hanging around.
tldr;
So, in general I don't try to organise my IDs and Classes by how they are used, and I try to maximise their reuse and minimise their changes. But I have an open mind if more compelling answers are given to this question!
I would say: classes (and targeting HTML elements directly or in combination) for styling, id's for behaviour (and Selenium), "do not repeat yourself/others" thinking - cascading styles, and that is about it.
If everyone follows this concept - common goal to keep clean code is achieved but at the same time it can also mean more problems - for example multiple event delegations (not using "proper" object oriented concepts) and CSS class chains on same element can cause even less readability and more time to handle.
So - actually it is very hard to have a general rule - especially if people have different views and code-styles. But I still think - classes for styling and id's for behaviour applies...

How to use jQuery without making a mess? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I could expect short answers to be "just use AngularJS/Backbone/...(fill the blank)".
But I believe before I dive into those ultimately, there shall be alternatives and proper ways of getting things done.
So for now, I am using plain html, css, javascript and the only library I use is jQuery and some plugins.
Confession time:
these are the things that I found myself doing all the time and I really think these are "bad" and not "the right thing to do":
Use global js variable to hook things together.
eg.
$(document).ready(function(){
window.someVar = ...;
window.someFun = function(){...};
});
Need to bind all the event again after DOM manipulation, because it stops working after selecting some elements and putting it somewhere else.
eg.
$(".myElementWithSpecialActionHandler").click(function(){});
after the element was relocated, say insert to a different position of the page, the event handler function stops working. So I have to do
// after DOM manipulation
// again >.<
$(".myElementWithSpecialActionHandler").click(function(){});
Js code is dumped into one giant "main.js" file.
css code is dumped into one giant "main.css" file.
I use <tag onClick="someFunction(); ...> here and there because of issue "2." sometimes.
I use inline css here and there.
I am a noob. But I am deeply uneasy writing all these code and yet I am not quite clear how to "make it right". I don't this is an ideal question in SO, but I think this is quite common for new developers. So the answers would benefit a lot of people.
Any enlightenment, web links, pointers to good source, help, and critics are greatly appreciated!
Yours sincerely,
A noob with good taste=> therefore he is disgusted with his own code :(
I don't think there are correct answers to any of these question, but preferences/opinions
1) I don't like adding variables to global scope, so window.someVar is a wrong practice because there can be accidental manipulation of a value by another non relevant scope. If you are using jQuery the need for global variables are very less. If you find yourself using it many times then you may have to rethink about the solution
2) You need to look at event delegation instead of binding event handler after creating new elements. Assuming you are adding new input elements to a div with id x then you can do the below in dom ready handler instead of binding it again and again
$('#x').on('change', 'input', function(){})
3) I normally uses a single js file for my script, so that it can be properly cached
4) same as the script file
5) In string literals I use ' as the enclosing tag so that I can use " inside for html attributes like var x = '<div class="someclass"></div>'.
6) I normally wouldn't use inline css, As much as possible try to separate style info from the html markup
Just to get it out of the way, you can definitely profit from using some sort of frontend framework. I like jQuery for small things that need to directly manipulate the DOM.
1) some of this is unavoidable. JavaScript is built on global variables. Even Douglas Crockford acknowledges this in "JavaScript: The Good Parts". Just try to keep it to a minimum. Look at patterns to contain things, such as immediately invoked function expressions.
3) Try to find ways to split things up then use something to concatenate and minify it. That said, I'm guilty of bunching things up too much too.
4) There are good reasons to split things out. Your CSS reset can be in its own file. Site-wide layout in another file. Page specific stuff can go into their own files. Templating languages can help you subdivide a page into functional pieces that can have their own CSS files.
5) I didn't know that this was a problem honestly. I've seen plenty of people use single quotes around JS strings.
6) Good for hacking, bad for long term. Just add another class (or id if appropriate). You could put it in a shame.css: http://csswizardry.com/2013/04/shame-css/

Mobile website too slow on the phone [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am building a prototype for a mobile section of a website. It uses no dynamic staff, just jQuery and Foundation 4. When I test the site in the iphone's browser, it's very very slow to load and to respond to touches. Can some experienced folks please tell me all things to make sure the site loads and operates faster on the mobile device?
All my images are saved "for web", so they shouldn't be a problem. Could it be slow because my CSS style sheet is very lengthy? I am not an expert at combining and applying one classes to a lot of things yet, so may be I have too many id-s and separate classes? Would that be a big deal in this case though? Also, could it be slow because I am using Foundation, jQuery and a Flexlider plug in and each of them has their own multiple style sheets and .js files? Should I throw away any files I am not using from their folders? Am I on the right track and what else can I do? Thank you in advance.
There are some things which helped me to make my mobile app more faster. I had the same issue as you, the screen response was very low.
Get rid of every unused code
I had a lot of commented code and files that i actually didn't use. This includes css styles that aren't used.
Do you even need classes or Ids?
Looking at my app, i had almost on any element a class or Id. Were i instead could use a element selector. here some more info about the selectors. Follow the DOM structure. I mostly used a class for groups and Ids for one specific element(which i almost never needed).
Check if you have css styles that doesn't add something
Sometimes you have multiple styles that doesn't actually add anything to it. A great example is using a float: *; and display: inline-block;. When using both of these on one element has no extra function as float makes the element inline-block by default.
optimize you script
With this i mean, see if you can shorter you codes with the same functionality. Using two almost identical functions? short them to one function. Also using premade function of your script language will really help you to make your code faster. So don't create your own sort function, but use the premade function.
For help on optimizing you code, i suggest you to take a look here.
jQuery selectors
Make your jQuery selectors more specific. For example:
You may have a div with class content.
<div class="content"></div>
Instead of selecting it with
$('.content')
You could use
$('div.content' )
jQuery can now restrict the search to DIV elements only.
More info fore more efficient jQuery selectors here
Store determenation code
When you get information, for example screenWidth minus the width of a other div, and you using this more then once, store it! This way your webpage hasn't to do the calculate over and over and can just get the variable.
Don't use 'big' plugins when using half of it
When you only use a small part of a plugin you're using, it's better to find or a other plugin or code it yourself. Loading the plugin files might harm your performence, would be a shame if it actually wasn't even necessary.
This is just a global view were I had a big advantage on and I hope you can find a fine use for this.
Feel free to correct me when I'm wrong.

When do you use DOM-based Generation vs. using strings/innerHTML/JQuery to generate DOM content?

I was wondering when to use DOM-based generation versus .innerHTML or appending strings using JQuery's .append method? I read a related post here Should you add HTML to the DOM using innerHTML or by creating new elements one by one? but I'm still unsure of the use case for each method.Is it just a matter of performance where I would always choose one over the other?
Let's say that form is an arbitrary variable:
DOM generation
var div = document.createElement("div"),
label = document.createElement("label"),
input = document.createElement("input");
div.appendChild(label);
div.appendChild(input);
form.appendChild(div);
JQuery
$(form).append("<div><label></label><input></input></div>")
The second one is more readable, although that comes from jQuery which does the innerHTML work for you. In vanilla JS, it would be like this:
form.insertAdjacentHTML("beforeend", "<div><label></label><input></input></div>");
...which I think beats even jQuery. Although, you should not worry about performance. The performance always depends on the amount of nodes to insert - for single ones, the HTML parser would be slower than creating them directly, for large HTML strings the native parser is faster than the script. If you really do worry about performance, you will need to test, test, test (and I'd say there is something wrong with your app).
Yet, there is a great difference between the two methods: With #1, you have three variables with references to the DOM elements. If you would for example like to add an event listener to the input, you can immediately do it and don't need to call a querySelector on form, which would be much slower. Of course, when inserting really many elements - with innerHTML -, you wouldn't need to do that at all because you would use delegated events for a real performance boost then.
Note that you can also shorten method #1 with jQuery to a oneliner:
var div, label, input;
$(form).append(div=$("<div/>").append(input=$("<input/>"),label=$("<label/>")));
My conclusion:
For creating only few elements the DOM approach is cleaner.
Mostly, html strings are more readable.
None of the two is faster in standard situations - benchmark results vary wide.
Personally, I don't like (direct) innerHTML for a few reasons, which are outlined well in these two answers and here as well. Also, IE has a bug on tables (see Can't set innerHTML on tbody in IE)
Generally speaking, hitting the DOM repeatedly is much slower than say swapping out a big block of HTML with innerHTML. I believe there are two reasons for this. One is reflow. The browser has to recalc for potential layout impact across potentially wide variety of elements. The other, I believe, and somebody correct me if I'm wrong, is that there's a bit of overhead involved in translating the stuff going on at the browser's post-compiled execution environment where rendering and layout state is being handled into an object you can use in JavaScript. Since the DOM is often under constantly changing conditions you have to run through the process every time with few opportunities to cache results of any kind, possibly to a degree even if you're just creating new elements without appending them (since you're likely to going to want pre-process CSS rules and things like what 'mode' the browser is in due to doctype, etc, that can be applied in a general context beforehand).
DOM methods allow you construct document fragments and create and append HTML element to those without affecting the actual document layout, which helps you avoid unnecessary reflow.
But here's where it gets weird.
Inserting new HTML into a node with nothing in it - close to a tie or something innerHTML is typically much faster at in a lot of (mostly older) browsers
Replacing a ton of HTML contents - this is actually something where DOM methods tend to win out when performance isn't too close to call.
Basically, innerHTML, if it stinks, tends to stink at the teardown process where large swaps are happening. DOM methods are better at teardown but tend to be slower at creating new HTML and injecting directly without replacing anything when there's any significant difference at all.
There are actually hybrid methods out there that can do pretty marvelous things for performance when you have the need. I used one over a year ago and was pretty impressed by response time improvement for swapping large swathes of HTML content for a lazy-loading grid vs. just using innerHTML alone. I wish I could find a link to the guy who deserves credit for figuring this out and spelling it out on the web (author, has written a lot of RegEx stuff too - couldn't google for the life of me).
As a matter of style vs perf, I think you should avoid tweaking the actual DOM node structure repeatedly but constructing HTML in a document fragment beforehand vs. using innerHTML is pretty much a matter of judgement. I personally like innerHTML for the most part because JS has a lot of powerful string methods that can rapidly convert data to HTML-ready strings. For instance:
var htmlStr = '<ul><li>' + arrayOfNames.join('</li><li>') + '</li></ul>';
That one-liner is a UL I can assign directly to innerHTML. It's almost as easy to build complete tables with the right data structure and a simple while loop. Now go build the same UL with as many LIs as the length of the arrayOfNames with the DOM API. I really can't think of a lot of good reasons to do that to yourself. innerHTML became de facto standard for a reason before it was finally adopted into the HTML 5 spec. It might not fit the node-based htmlElement object tweaking approach of the DOM API but it's powerful and helps you keep code concise and legible. What I would not likely do, however, is use innerHTML to edit and replace existing content. It's much safer to work from data, build, and swap in new HTML than it is to refer to old HTML and then start parsing innerHTML strings for attributes, etc when you have DOM manipulation methods convenient and ready for that.
Your chief performance concern should probably be to avoid hammering away at the 'live' portions of the DOM, but the rest I would leave up to people as a matter of style and testing where HTML generation is concerned. innerHTML is and has for years now been in the HTML5 working draft, however, and it is pretty consistent across modern browsers. It's also been de facto spec for years before that and was perfectly viable as an option since before Chrome was new, IMO but that's a debate that's mostly done at this point.
It is just a matter of performance. Choose the one that fits you best.
jsPerf is full of those performance test, like this one: test

Categories