Mobile website too slow on the phone [closed] - javascript

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.

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/

When should I control background image change with CSS vs Javascript? [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 9 years ago.
Improve this question
This is more of a general practice question that a problem specific one but I'll give an example of what I mean. There are a lot of things you can control with CSS that you can also do with Javascript, but is one better to lean on than the other?
Example:
I have four buttons in a nav that are given a class of "selected" when the section they're associated with is in view. So I could either write a CSS statement for each button (or have Sass do it for me with a mixin)
#home-butt.selected{
background-image: url(images/home-up.png);}
#about-butt.selected{
background-image: url(images/about-up.png);}
#work-butt.selected{
background-image: url(images/work-up.png);}
#contact-butt.selected{
background-image: url(images/contact-up.png);}
Orrr I could write something in javascript to do the same thing. (*I gave the images a title attribute that matched the image name so it could pull from there).
title = $(this).attr('title');
$(this).find('img').css("background-image",
"url(" + 'images/' + (title) + '-up.png' + ")");
So my question is which is better to use? Is it the javascript because it's less lines of code? Or the CSS incase javascript is disabled? Or is this a very situational question where there isn't always a right or wrong answer?
Opinions and rebuttals are welcome!
To answer your question about "is one better to lean on than the other?"
Keep in mind, that CSS has a specific purpose. To apply the look to your application. JavaScript on the otherhand, is mostly the feel of your app. Always prefer CSS over JavaScript when editing styles.
The only time that you ever should modify styles using JavaScript is when you have a dynamic application, and need to change styles based on some unknown variable. Even then, a lot can be achieved with just using CSS.
Also keep in mind that you are using jQuery. think about jQuery's constructor. it is a CSS selector.
With the concept of CSS pseudo-classes introduced, there is very little that you cannot achieve style-wise with CSS.
In many cases where Javascript developing makes what I'm trying to accomplish much more easy and other cases where CSS does that to.
" In the end each "language" has its appropriate place in web development and used wisely can enhance both development and user experience. Learn what those uses are (I recommend experience learning) and apply wisely. In my experience, set in stone rules such as "Never use JS when a CSS solution exists" (paraphrased) are rarely best in the practical world. "
If you are working with layout, use CSS, if your creating the look and feel use CSS, if your doing animations use CSS3
If you attach event handlers or reacting to user input use JavaScript.
Usually you want to use CSS, because it's much faster than javascript. Also there are going to be users with javascript disabled, which aren't going to see your enhanced presentation if it relied on js function.
The usual answer is, use CSS when you can, because it will work with JavaScript disabled, and also because you don't have to deal with issues like waiting for elements being available in the DOM before referencing them.
But sometimes it depends. Keep in mind that:
Depending on the selector or properties you're changing you may have issues with browser compatibility.
If you're changing the image like in your example, you may see it flicker while the new image is loaded. You can avoid that by using a sprite image, or preloading the images with JavaScript.
As a general rule of thumb, I would use CSS for styling and JavaScript only to "make the page alive".
So the best and the most ideal use of JavaScript is to add and remove classes from elements
- classes, which your CSS is depend on.
Loading the jQuery library to perform this simple task is unnecessary and relying on javascript to apply background images to your img tags is unnecessary as well.
If it can be done properly in CSS, and work in all browsers, then it should be done in CSS.
Javascript is for more advanced or complex tasks, which require interaction or animations that CSS can't provide for all browsers (due to cross browser compatibility issues - check out caniuse.com)
In your example, if the .selected attribute is being given dynamically by javascript for instance:
makeSelected(elm)
{
document.getElementById(elm).className='selected';
}
then i would still personally add the styling for .selected in CSS instead of adding the image through javascript.
If you're adding .selected based on the current page you're on and not through javascript then I would recommend using CSS.
I prefer CSS over Script for one main reason Browser compatibility
There are just soooo many times when one script code or the other isn't compatible in one browser or the other (cough or just IE)
With css I haven't had such issues yet (touchwood) and also if there were any issues CSS's won't affect as much as script's which just don't let any other following codes to execute.
Let me provide my opinion.
Personally I don't believe a website should have a lot of "gimmicks" in terms of designing.
BY gimmicks I mean hovering effects, music in the background(absolute no-no) or other "eye-catching details". All of this looks good the first time but subsequently visitors get fed up with this distractions.
Without deviating from the main issue. CSS/JavaScript for styling.
Well they do exist hand in hand. The best example for this would be Bootstrap library. Although I have never used it personally but it seems amazing what can be achieved using CSS and JavaScript.
So, We will need both to design spectacular website. CSS helps in the basic designing and to make the website more responsive we use JavaScript and its derivative libraries like Jquery for all the finer looking stuff

Javascript widget implementation

I have a question about Javascript widgets. The widget I am working on simply embeds content on a page instead of using iframes. So far it looks good. But there are cases where some users layouts are messing up the widget. For example, the widget might require a width of 300px to appear. But the parent div is set to 250px and hence the right part of the widget is cut off.
I was wondering what sort of precautions should be taken to prevent this? I was talking to the product manager who mentioned he wanted me to check the parent div elements and get the size and then show an alternate message if their size is not accurate. But again, since this is Javascript and the widget is supported in many diff browsers(including IE6), I am wondering how fail-safe this method would be? What if I need to iterate the DOM all the way up before getting a valid size? I am also worried about performance here. This extra checks would slow down the delivery of my widget content to "good users" since I am adding a layer of complexity to all users. I don't want to penalize good users just because of the few errant ones.
I am not using any sort of JS library here, so any solution should not suggest the use of one. Also, the reason for not using a library was simply not to add extra weight to the page load to deliver a widget. I understand that "jquery" for example is small, but in my case, even 24k compressed seems like an overkill for a widget delivery that contains no core code for the widget.
Has anyone dealt with such issues before? What are your solutions to these?
There are reliable ways of determining the size of an element using JavaScript. You're quite right that you may need to iterate up the tree in some cases, but the answer you get will ultimately be quite valid.
Although you don't want to directly include any library code in this project, you may consider looking at how the major libraries implement their "what's the width of this element" functions to drive your own implementation.
Beware of quirks mode too.
I'd check to see of the page has Jquery, if not load it into the page using no-conflict mode. Then use jQuery to examine the page.
See: How to embed Javascript widget that depends on jQuery into an unknown environment

Categories