Is the downside of coding styles (css) in jQuery genuinely prohibitive? - javascript

I was just reading an article about the non-compatibility of some CSS, when it occurred to me that maybe I should be writing all of my CSS in jQuery. Aside from javascript-disabled browsers, which any ajax website isn't going to support anyway, what's the downside?
The benefit, aside from greater browser support, would be the use of variables throughout the (pseudo) css file. I could control a color across borders and backgrounds etc. in a single place. I know this has been done with backend programming, but I'm seriously considering it with front-end. Anyone wanna talk me off the ledge?
The article I was reading is here, if you're interested:
http://www.impressivewebs.com/buggy-css-selectors-cross-browser-jquery/

Javascript-disabled browsers, like you say. More people have Javascript turned off than CSS turned off.
Secondly, I imagine the performance will be worse on the clients-end.
In general, CSS goes at the top. This means that the browser can style the HTML as it loads, rather than waiting for all the HTML to load. With Javascript, unless there are some really fancy tricks which I don't about it, you would need to wait for the HTML to load before you could do your styling, resulting in a FOUC
Also, browsers are also heavily optimised to execute CSS as efficiently as possible.
There are more reasons... plenty more.

Before I get to the reasons I will just say without even giving this any thought whatsoever it sounded like a bad idea. Sure there might be some CSS that is incompatible across browsers but those situations are definitely a minority. Remember CSS is a standard. So the majority of it is going to be implemented across the board.
But for the more logical reasons:
Performance would be a major issue to consider as now your clients browsers are going to have a lot more to process. Plus js is linear so everything would have to wait for the prior function to finish, there are some workarounds to this, but for the most part this could be a big issue.
What you can accomplish in a few lines of css could be several more with js. And that would be per page since you couldn't really reuse a lot of it.
What happens when you leave your place and a new developer comes in and wants to change styles across all pages. Guess what he's screwed?
I can't even seeing this saving you anytime because with css you can write in one place and apply everywhere. With your js solution you would have exponentially more code to maintain.
The other reason you mentioned with js turned off. Sure your ajax calls aren't going to work like you mentioned so there will be some problems but at least they will be able to see what your site looks like without just seeing a bunch of text everywhere.
I could go on but I think you get the point this is not a good idea by any means.
Of course, this is just my opinion so take it for whatever it is worth. But I think you would seriously regret this decision.
EDIT: Sorry for the novel. One last thing though, the article you referenced was about CSS selectors and not overall css.

Related

what is unobtrusive in Passport.js [duplicate]

What is the difference between obtrusive and unobtrusive javascript - in plain english. Brevity is appreciated. Short examples are also appreciated.
No javascript in the markup is unobtrusive:
Obtrusive:
<div onclick="alert('obstrusive')">Information</div>
Unobtrusive:
<div id="informationHeader">Information</div>
window.informationHeader.addEventListener('click', (e) => alert('unobstrusive'))
I don't endorse this anymore as it was valid in 2011 but perhaps not in 2018 and beyond.
Separation of concerns. Your HTML and CSS aren't tied into your JS code. Your JS code isn't inline to some HTML element. Your code doesn't have one big function (or non-function) for everything. You have short, succinct functions.
Modular.
This happens when you correctly separate concerns. Eg, Your awesome canvas animation doesn't need to know how vectors work in order to draw a box.
Don't kill the experience if they don't have JavaScript installed, or aren't running the most recent browsers-- do what you can to gracefully degrade experience.
Don't build mountains of useless code when you only need to do something small. People endlessly complicate their code by re-selecting DOM elements, goofing up semantic HTML and tossing numbered IDs in there, and other strange things that happen because they don't understand the document model or some other bit of technology-- so they rely on "magic" abstraction layers that slow everything down to garbage-speed and bring in mountains of overhead.
Separation of HTML and JavaScript (define your JavaScript in external JavaScript files)
Graceful degradation (important parts of the page still work with JavaScript disabled).
For a long-winded explanation, checkout the Wikipedia page on the subject.
To expand on Mike's answer: using UJS behavior is added "later".
<div id="info">Information</div>
... etc ...
// In an included JS file etc, jQueryish.
$(function() {
$("#info").click(function() { alert("unobtrusive!"); }
});
UJS may also imply gentle degradation (my favorite kind), for example, another means to get to the #info click functionality, perhaps by providing an equivalent link. In other words, what happens if there's no JavaScript, or I'm using a screen reader, etc.
unobtrusive - "not obtrusive; inconspicuous, unassertive, or reticent."
obtrusive - "having or showing a disposition to obtrude, as by imposing oneself or one's opinions on others."
obtrude - "to thrust (something) forward or upon a person, especially without warrant or invitation"
So, speaking of imposing one's opinions, in my opinion the most important part of unobtrusive JavaScript is that from the user's point of view it doesn't get in the way. That is, the site will still work if JavaScript is turned off by browser settings. With or without JavaScript turned on the site will still be accessible to people using screen readers, a keyboard and no mouse, and other accessibility tools. Maybe (probably) the site won't be as "fancy" for such users, but it will still work.
If you think in term's of "progressive enhancement" your site's core functionality will work for everybody no matter how they access it. Then for users with JavaScript and CSS enabled (most users) you enhance it with more interactive elements.
The other key "unobtrusive" factor is "separation of concerns" - something programmers care about, not users, but it can help stop the JavaScript side of things from obtruding on the users' experience. From the programmer's point of view avoiding inline script does tend to make the markup a lot prettier and easier to maintain. It's generally a lot easier to debug script that isn't scattered across a bunch of inline event handlers.
Even if you don't do ruby on rails, these first few paragraphs still offer a great explanation of the benefits of unobtrusive javascript.
Here's a summary:
Organisation: the bulk of your javascript code will be separate from your HTML and CSS, hence you know exactly where to find it
DRY/Efficiency: since javascript is stored outside of any particular page on your site, it's easy to reuse it in many pages. In other words, you don't have to copy/paste the same code into many different places (at least nowhere near as much as you would otherwise)
User Experience: since your code can is moved out into other files, those can be stored in the client side cache and only downloaded once (on the first page of your site), rather than needing to fetch javascript on every page load on your site
Ease of minimization, concatenation: since your javascript will not be scattered inside HTML, it will be very easy to make its file size smaller through tools that minimise and concatenate your javascript. Smaller javascript files means faster page loads.
Obfuscation: you may not care about this, but typically minifying and concatenating javascript will make it much more difficult to read, so if you didn't want people snooping through your javascript and figuring out what it does, and seeing the names of your functions and variables, that will help.
Serviceability: if you're using a framework, it will probably have established conventions around where to store javascript files, so if someone else works on your app, or if you work on someone else's, you'll be able to make educated guesses as to where certain javascript code is located

Removing jQuery for performance reasons justified?

I am on a new project and our job is to rewrite an e-commerce website that is having performance problems on mobile devices.
We are re-writing the javascript based on a more object-oriented/modular architecture which I think is great! However my team lead said that we should remove all the jQuery calls and replace with javascript like so domElem.querySelectorAll(query) , which has better performance. I understand jQuery does some kind of caching in the background which can create memory issues.
I am a little sceptical of this, firstly because it seems like a case of 'premature optimization', that is, we should find the bottle-necks first before we re-write anything. And secondly I haven't found anything on the internet that says that jQuery has significant performance problems.
The current website does have a lot of overlapping dom branch queries which I think creates a lot of redundancy. That is there is too much querying happening, and on our new architectual approach we are restricting our object/module to fewer dom queries and more targeted dom queries which is great. This does need to be re-written.
But whether or not we use domElem.querySelector(query) or $(domElem).find(query), I can't see there as being much of a difference. Is my thinking right?
Some tests are done here (check other revisions as well). Good detailed discussion is done here over pros and cons of using jquery over javascript.
Also want to point out that jquery doesn't do any caching of selectors.
The thing we often forget because of using Javascript frameworks all the time is that jQuery is not a framework.
Obviously, if you do the exact same one-operator action using the jQuery '$' object and using a direct DOM method like getElementById, the latter will be noticeably faster as jQuery itself is written in Javascript and does a lot of background stuff.
However, nothing (except code readability) prevents you, as a developer, from combining jQuery with plain Javascript: using plain Javascript wherever possible and only using jQuery functions that provide complex functionality and take some time to write and optimize from scratch. There are a lot of those in jQuery: providing browser-independent css, serializing object and doing lots of other cool stuff.
It depends on the application but usually performance troubles are related to badly-designed algorithms, not the use of jQuery.
In any case, if your application does a lot of DOM-manipulation, it may be worthwhile to re-write it using plain Javascript and test. Keep the library, just don't use it for simple operations you can easily write without it.
If your application is heavily-reliant on jQuery functions with complex functionality, removing it is out of the question.
I myself use this combined approach: everything simple written in Javascript with jQuery functions for stuff that is difficult to implement.
Also, a good place to dig around if the app has troubles with performance is the DOM-manipulation. Those operations are very heavy compared to almost everything else in Javascript. You may be able to cut down on time by rolling several operations into one, building finished objects with one constructor, instead of creating empty ones and assigning properties one-by-one, etc.
Sorry, if the answer is a bit vague but it's difficult to be precise in this case without seeing the code and running tests.
Let me quote Uncle Bob about this discussion "Architecture is about intent, we have made it about frameworks and details"
Premature optimizations needs to be considered carefully.
They often result architectural decisions that are not easily revertible.
They introduce code optimizations that are usually specific to the problems they solve, which makes the code less abstract thus hard to
maintain, and more complicated thus prone to more bugs.
They tend to be prejudice and not objective, sometimes without any real comparison to other alternatives.
The problems they are trying to solve tends to be overestimated, to the degree of non-existent.
I'm not a big expert on Web development but if possible, you should always push this kind of decisions to the end by separation of concerns, and good abstraction.
For example over the parts that generate the java-script code you can have an abstraction of JavaScriptWriter, and use different frameworks. This way you can use JQuery at the beginning, test the system and only then replace parts you know to be inefficient.

How to debug user entry issues in JavaScript with WebKit developer tools?

I have an issue where input is being doubled, tripled, quadrupled, etc. on user input after changing a select dropdown multiple times. Here's a small video showing my dilemma and posing the question: http://screencast.com/t/7Gb01nGe787p
Essentially the question is how to debug properly given circumstances like this?
I think how you debug depends heavily on how your code is structured.
If you are using widgets(jquery UI stuff, plugins, external libraries etc) you can always search around and see if its a known bug/issue. Aside from that, checking configurations(I've been burned by config's not being correct several times) can be helpful. Also check for conflicting code, such as events you may have defined that could interfere with the widgets behavior. Manipulating objects in the webkit console is particularly useful for this, since you can more easily find out in what cases your code will work, and in what cases it will not, without necessarily having to rely on manipulating the UI.
If you are not using something other people wrote, then debugging is a little easier in my opinion. For me, it really comes down to narrowing the scope of where I am looking. If you have any events related to your issue(onKeyUp or something), log it. Console.log can go a long way, especially when dealing with the state of UI, and so can breakpoints. I'm not sure if this is necessarily the best way to do it, but I find it to be very useful in the right situation.
If you are really stuck, you can always get drastic and start removing pieces of your code. May not sound very nice, but if you are really stuck and cannot seem to find what section of code is being problematic it will at least give you an indicator of where to look. Again, not the prettiest solution, but it's saved me a lot of headaches on more than one occaision.
Hope this helps.

Is having too many setTimeout()s good?

I'm using mostly Javascript on my scripting. I have some scripts which do several tasks every 1 second, and some every 0.02 seconds, etc. My intervals do tasks like checking of ifs, doing some innerHTML, little animation, etc. Now I have 4, but I think it would increase in the future; maybe I'll control myself to less than 10. Though it doesn't lag at all in my computer.
Generally, will it be good for a site?
Since it's client-side obviously there won't be any issues with internet connection, right?
Is it a bad practice, or is it not much of an issue at all?
Also, I have a question for jQuery. There are things that normal Javascript and jQuery can do similarly (like innerHTML and .html()), right? Given this situation, which should I prefer to use, jQuery or Javascript?
Thank you.
Is having too many setTimeout()s good?: You already gave your self the answer too many is not good, no matter what you talk about.
Generally will it be good for the site: Probably not, remember you don't know the cpu/browser combo of your users, so you should build your site so it will still be nice to use for people who have slower computers than you. A laggy/unresponsive site is the first one users will flee from.
Since it's client-side obviously there won't be any issues with internet connection, right? right, unless you do network requests as part of the timeouts. Ajax calls every second is rarely a good idea.
Is it a bad practice, or is it not much of an issue at all? poor architecture is bad practice. If you wish to follow the best practices, read up on design patterns.
Also, I have a question for jQuery. There are things that normal Javascript and jQuery can do similarly (like innerHTML and .html()), right? Given this situation, which should I prefer to use, jQuery or Javascript? Using jQuery gives you convinient crossbrowser compatibility. In most cases for non-experts using a library like jQuery is better than not using it.
Generally, will it be good for a site?
Most of the other answerers are saying no, but they can't possibly make this claim without more information. This decision is specific to your site. It might be perfectly fine. Don't make guesses about performance. Measure things. Fix performance issues where they really exist, not where your gut tells you they exist.
Since it's client-side obviously there won't be any issues with internet connection, right?
Correct.
Is it a bad practice, or is it not much of an issue at all?
There are lots of tasks that are best performed with a timeout callback. If you need to do something periodically, or after a certain amount of time has passed, then setTimeout is not only reasonable to use, it's specifically designed for those tasks.
For your first question, it's more a case of what you're doing in each callback that gets called after the timeout. Without knowing that it's hard to provide a clearer answer.
But remember that javascript is single threaded in the browser, so if you're running expensive operations regularly it's not going to work well. If you're looking to do animations with this, I'd strongly urge you to consider one of the existing libraries first (dojo, jquery, mootools etc) and only try and implement this yourself if you find them insufficient. A lot of work has gone into making those libraries performant and it's unlikely you'll do better on a first stab.
Second question: Again, I'd use the library. For a simple innerHTML there's unlikely to be much difference, but in the general case a library like jQuery or Dojo will help to cover over the differences between the DOMs in the different browsers, catch the nasty edge cases you don't know (or want to know) about and is likely to be better tested and supported than your own code. Get it working their way, then optimise with your own vanilla JS if/when you need to.
1) Generally good: no, in general it creates processor load, which slows down the browser. But that will be influenced more by the actual code than the timeouts itself. But modern day browser don't have any problems with 10 timers... ;)
2) Yeah, no problem with the timeout.
3) No, it's the only way to do asynchronous processing. so it isn't really an issue ;)
4) The difference with innerHTML and .html() (and other jQuery functions) is that jQuery has better cross-browser implementations. It knows the quirks of certain browsers and is able to circumvent them. For simple problems plain 'ol JavaScript is perfect (and is cheaper in bandwidth and processing power). But for more complex scripts, and once you have chosen to use jQuery, why not use it anyway. ;)
Go with Jquery - Write Less, Do More
You can have so many functions , effects , plugins will help you to save time from coding.
Any way when you are developing a website with javascript or jquery effects , you will be expecting the user should have an updated browser and system.
your functionality not gonna work on ie 5 . :)
So adding time out and js functions will not affect performance as per my understanding.
http://api.jquery.com/delay/
http://api.jquery.com/toggle/
http://api.jquery.com/html/
Go with jquery api functions and develop your own..instead of usng plugins.

Using multiple Javascript frameworks in a project?

Is it good or okay to have several frameworks in a project, or is it bad because it gets cluttered (= a mess), and the loading times maybe get's longer. Does some 100 K matter really? Or should you stick with one?
It's generally better to pick one thing and stick with it, for a number of reasons:
Fewer dependencies.
Lower complexity.
Easier to maintain.
Faster loading times.
No likelihood of dependency conflicts (i.e. jQuery can't conflict with your other Javascript framework if you only have one).
Lower debugging times.
It's true that an extra ~50k these days probably isn't going to kill anybody for a personal site or blog. The benefit comes when you scale to larger sizes, and all those extra 50k hits are eating into your bottom line. But even if you're just doing this for a small site, the savings on your sanity from figuring out problems quicker will easily be worth it.
That said, if you just need one part of a specific piece of a Javascript framework, the larger ones are often split into logical chunks, so that you can just take the piece you need rather than the entire framework. Most are rich enough these days that if framework X has a feature you want, but you're using framework Y, you can pretty much just map the source code for that feature directly into framework Y.
If you can load the javascript library from a repository where it would be cached on the first visit, then i don't really see any problem with that.
But, for uniformity sake i will go with one javascript library.
But, if you really have any strong reason to use two, then go ahead. As far as it is cached the first time.
Just adding something to John's words, one could choose, for example, JQuery, which allows you to use it without clashing with other libraries. I remember that once, I had troubles while trying prototype and mootools because I wanted some things from the former and some other from the latter, but it was long ago and maybe it was solved.
Somehow, I've found that it's easier to maintain a single library and there're a few real differences between them. It related more to the way each one approaches to map documents and apply things to their elements, which causes differences in response time, but the goal happens to be the same.
Good luck with your choice :)
PS. If you gzip and fix etags in the stuff you offer in your webapps, the difference between loading one or two js frameworks is not reeeeaaally important -unless you're in facebook, meebo or so!-. I've found that the yahoo! recommendations are helpful.
http://developer.yahoo.com/performance/rules.html
I wouldn't run two frameworks unless there was really no alternative. They often aren't written to play well with others; there are lots of potential ways they can cause unwanted interactions.
For example with jQuery, a lot depends on the user-data key identifiers the library adds as attributes to element nodes. If you start messing with the structure of the document by cloning, adding/removing and so on from another framework (or even just plain DOM methods) then those identifiers aren't as unique as jQuery expects; it can easily get confused and end up failing to call event handlers, or tripping on errors. This sort of thing isn't fun to debug.

Categories

Resources