Last Updated on January 27, 2022
As seen on Github.
General Questions:
What did you learn yesterday/this week?
How to develop IOS and Android apps with the AngularJS powered Ionic framework. Read more about Ionic
What is a recent technical challenge you experienced and how did you solve it?
Creating an interface (for Progressive Insurance) that allowed for users to filter results in a large list with a proprietary, hierarchical system. Users could then add or remove those items to another list of “saved” items. The filtering system could be adjusted, yet retain the saved list through the process until they “save” to DB or print. View the full prototype version (hit escape to remove spinner) or view a pen of the table manipulations:
What UI, Security, Performance, SEO, Maintainability or Technology considerations do you make while building a web application or site?
UI: Depending on your audience, accessibility can be your biggest challenge and resources such as http://a11yproject.com are great in suggesting patterns to achieve whats needed. Beyond that, a pleasant palette and intuitive interfaces are the foundation, which arise from well developed style guides containing code snippets that help developers quickly deliver features with pre-themed UI elements that alleviate common pain points such as non-conforming elements that may distract stake holders during the iteration and approval process.
Security:
Login pages should be encrypted
Data validation should be done server-side
Manage your Web site via encrypted connections
Talk about your preferred development environment.
Typically I use Sublime Text with a local server. As I state in my work history I have been involved in a vast variety of dev teams, each with it’s own flavor. Most recently I worked at Aspect Software, a Microsoft shop, where I embraced IIS, Visual Studio, Team Foundation Server, Office 365, One Drive, Share Point and more. As an aside, upon employment I was issued a Windows Phone and found the interface very exciting despite the lack of applications built for it.
Which version control systems are you familiar with?
Git, Bitbucket, SVN, TFS.
Can you describe your workflow when you create a web page?
Here I describe “My Process” in detail.
If you have 5 different stylesheets, how would you best integrate them into the site?
Break them up onto to different CDN servers to leverage domain sharding.
Employ the “new old” technique of adding “above the fold” css inline in the head of your document – reducing http requests and improve perceived performance.
Using SASS I would break up my files into related chunks – all of which are concatenated and compressed using compass, sass with gulp or grunt in your build process.
Can you describe the difference between progressive enhancement and graceful degradation?
Graceful degradation is when you initially serve the best possible user experience, with all modern functionality, but use feature detection to “gracefully degrade” parts of your application with a fallback or polyfill. You could use Modernizr like this:
How would you optimize a website’s assets/resources?
Concatenate and compress CSS, JavaScript and HTML files wherever possible, configure your server to deliver a Gzip files, cache resources, set longer expirations dates on http headers of resources you don’t expect to change often – such as a logo. Images can be some of the heaviest files we deliver, so compress wisely. Soon the picture
element will be implemented across browsers, so we can optimize the delivery of image content. Also in the near future consider using WebP format for images – it is quite smaller in size than JPEG and PNG files. Finally, use a CDN or other domains to host your resources and leverage domain sharding.
How many resources will a browser download from a given domain at a time?
Approximately 6. IE leads the pack with 8.
What are the exceptions?
When downloading different resources from multiple domains – also known as “domain sharding.”
Name 3 ways to decrease page load (perceived or actual load time).
1) LocalStorage 2) Caching resources 3) dns-prefetch (sample below) 4) Keep resources on a CDN
If you jumped on a project and they used tabs and you used spaces, what would you do?
Get used to it and adjust. Adjusting and adapting are some of my greatest strengths.
Describe how you would create a simple slideshow page.
If you could master one technology this year, what would it be?
Angular ng-animate. I have been studying AngularJS and JavaScript very intensely, and being the “design guy” means I need to make applications pop and shine. When committing to a framework like AngularJS -it’s best to use their way of coding to maintain consistency and help future developers understand the “what, why and how” of the application. Furthermore, when you stick to the chosen framework’s way, you inherit documentation as well.
Explain the importance of standards and standards bodies.
To ensure new tools, and methods maintain backwards compatibility, and that new concepts and methods are well documented and agreed upon as THE best solution to certain issues – currently we can see this in action regarding responsive images.
What is Flash of Un-styled Content? How do you avoid FOUC?
When page content displays before styling resources are rendered. Being that CSS is a blocking resource, you can avoid FOUC by putting all of your <link>
references in the head of your document – forcing CSS to download before the html.
Explain what ARIA and screen readers are, and how to make a website accessible.
Screen readers are software programs that provide assistive technologies that allow people with disabilities (such as no sight, sound or mouse-ing ability) to use web applications. You can make your sites more accessible by following ARIA standards such as semantic HTML, alt attributes and using [role=button]
in the expected ways.
Tips
Using ARIA
A11Y Project
Explain some of the pros and cons for CSS animations versus JavaScript animations.
Regarding optimization and responsiveness the debate bounces back and forth but, the concept is:
CSS animations allows the browser to choose where the animation processing is done, CPU or the GPU. (Central or Graphics Processing Unit)
That said, adding many layers to a document will eventually have a performance hit.
JS animation means more code for the user to download and for the developer to maintain.
Applying multiple animation types on an element is harder with CSS since all transforming power is in one property transform
CSS animations being declarative are not programmable therefore limited in capability.
What does CORS stand for and what issue does it address?
Cross Origin Resource Sharing. To address the fact that browsers restrict cross-origin HTTP requests initiated from within scripts. CORS gives web servers cross-domain access controls, which enable secure cross-domain data transfers.
What does a ‘doctype’ do?
Let’s the browser know the version of and language of the document.
What’s the difference between standards mode and quirks mode?
Quirks mode was to support websites built before standards became widely implemented.
What’s the difference between HTML and XHTML?
The Extensible Hypertext Markup Language, or XHTML, has two important notes for front end developers. 1) It needs to be well formed, meaning all elements need to be closed and nested correctly or you will return errors. 2) Since it is more strict than HTML is requires less pre-processing by the browser, which may improve your sites performance.
Are there any problems with serving pages as application/xhtml+xml?
Strictly though, you should take into account the q values in the accept header that indicates the preference of the user agent to each content type. If a user agent prefers to accept text/html but will accept application/xhtml+xml as an alternate, then for greatest safety you should have the page served as text/html.
How do you serve a page with content in multiple languages?
Programmatically reset the:
cookie sessionStorage localStorage
cookie
: A text file saved on the users computer to store and retrieve datasessionStorage
: Is memory space in a browser to save temporary data until the window or tab is closed.localStorage
: Like cookie, where data can be saved and retrieved after browser sessions, but stored in memory like sessionStorage. Data is stored as plain key value pairs and can be stored as Json objects.
// Stored as Json
var dataToStore = JSON.stringify(data);
localStorage.setItem('someData', dataToStore);
// Retrieve
var localData = JSON.parse(localStorage.getItem('someData'));
I made a pen exploring localStorage:
Normal Execution:
script
:Parsing of the HTML code pauses while the script is executing. For slow servers and heavy scripts this means that displaying the webpage will be delayed.
Deferred Execution: script defer
Delays script execution until the HTML parser has finished. A positive effect of this attribute is that the DOM will be available for your script. However, since not every browser supports defer
yet, can’t rely on it.
Asynchronous Execution: script async
HTML parsing may continue and the script will be executed as soon as it’s ready.
CSS goes in the head to calculate the styles and layout before DOM elements load to prevent flashes of un-styled content. Loading JS just before the body close means the DOM will be available for it.
However, modern browsers have implemented ‘speculative parsing’ – where the browser ‘looks ahead’ in the HTML and begins downloading resources before scripts download and execute. (reference)
34) What is progressive rendering?
It is rendering the data as it’s being downloaded. This is particularly useful on documents that have tons of text. You can see it on a page that has a lot of text – and where the scrollbar will get shorter in length as more data comes in – increasing the vertical size of the document – yet, it would display the downloaded text immediately. As more data came down the pipe – the page would get longer. This didn’t rely on the closing body or html tag – and it certainly wouldn’t render the entire page on the server – then download – which is a standard complaint about modern frameworks. But there is a technique called “Flushing the Buffer” that can be implemented on the server. I don’t know that much about the technique, but found a few resources discussing it. Ref 1 Ref 2
No. I’ve only yet written html in full. But, I am looking into Jade as I write this.
CSS Questions:
Classes are reusable CSS reference selectors named
class=
in the HTML document and prefixed by a period in a stylesheet. ID’s are declared as id=
in HTML and referenced by the # (hashtag.) ID’s are designed for unique specificity since they can only ever be used by JavaScript once. Though styles applied by ID through CSS do affect all instances of the ID.
Resetting is setting all default (user agent) tables, blockquotes, margins, padding, borders, ul, ol, to 0 – forcing the designer to re-style every element as it comes into play. Normalizing is a newer approach which leaves many of the default styles in place, some added opinions but most importantly, it addresses many of the cross browser quirks for you. I prefer using normalize as it can make creating forms much faster.
Floats are a position property that is handy in setting up flexible combinations of elements as well as page layouts. For layout, the
clear:
becomes essential in keeping things stacked as you expect. A floated element can misbehave, if it can squeeze up and in – it will. Of course the biggest quirk is the parent collapse issue. If you have several floated elements inside a parent – the parent will collapse to a height of 0. To address this, the ‘clear float’ method has become a varied science in itself. But usually I choose the overflow: auto;
, or the pseudo element clearfix method. And mind you, flex-box is around the corner, so modern layout is about to get much easier.
By default, an elements stacking order is how it appears in the html. Once positioning and z-index is added, each parent of a group of elements creates a new stacking context. Admittedly, it’s pretty complex, but I haven’t had many situations where more than two z-index / stacking arrangements were needed. I created a pen to illustrate this:
As mentioned earlier in the ‘floats’ question, there are essentially three, 1) ‘add a div’ method, 2) the overflow:auto on the parent method, 3) the classic clearfix and now the 3a) micro clearfix. Both mimic the ‘add a div’ method except that it uses a pseudo element in place of an extra div for leaner HTML and better semantics.
Sprites are when you combine 2 or more images in one single graphic file in order to reduce http requests. You would then place the image into a specifically sized container, then adjust the background-position of your sprite-image to ‘show through’ the correct part of the image. Here is a pen to show it in action:
Chris Coyier of CSS-Tricks has created an historical record of all the different techniques used throughout the years. I have used this technique very seldom since most of the applications I have built didn’t require it. But here is the latest technique, initialized by Jeffery Zeldman and tweaked by Scott Kellum (Ref)
.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}
.screen-reader-text {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
Classically the biggest culprit was IE, (post-Netscape) and the easiest fix would be to load a supplementary stylesheet to add hacks and fixes for the css that needed it. A second technique was adding a second line of css with an ‘unrecognized by others’ character so it was ignored by all other browsers.
// Additional Stylesheet
// Unrecognized Characters and 'End of Line /9' Hack.
// There are so many similar IE hacks like this
// Check Paul Irish's link below for the definitive list (2009)
.lte-ie8 .name {
color: green; /* IE8 and older */
*color: blue; /* IE7 and older */
_color: red; /* IE6 and older */
}
#name { color: blue\9; }
Paul Irish has an extensive list to refer to when and if these types of issues arise. Also to note, earlier I discussed using ‘normalize’ over ‘css reset’ – part of that reason is because it addresses many of the cross browser form element quirks you will find.
I use Modernizr as the check and then address issues like this:
One technique could be ‘UA sniffing.’ The UA String gives you the rendering engine version, the OS and the device so you can serve specific pages that way. I don’t have much experience with setting a server to accommodate browser constraints.
.hidden {
position: absolute !important;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
padding: 0 !important;
border: 0 !important;
height: 1px !important;
width: 1px !important;
overflow: hidden;
}
I’ve used Bootstrap, Foundation, Skeleton and rolled my own. I prefer rolling my own to keep a naming system that I prefer and not rely on (potentially) bloated systems that have a lot of css I would not use, but there are two advantages to using a framework/library: 1) They typically have a lot more eyes on the code as well as devices to test on, so it may be safer, particularly in edge cases 2) For prototyping you can’t beat the speed to discovery process.
At this point I think most front end designers and developers have experienced using media queries – either through a mobile framework or writing their own. I personally have used them for responsive applications and found with the help of SASS nesting, it can remove a lot of complexity. But there is much more to media queries than
@media and screen(){}
– so I spent some time setting up a codepen with all the media queries in action:The simplest implementation, uses a limited cascade which gives you have the ability to style the fill and color of SVG objects using the elements and attributes
svg, use, symbol, path and inherit
. Basically, you are setting up a a fill and path SVG object, reusing that math to repeat and add limited stylization. Here is an example:Being a designer, I’ve had awareness of Adobe Illustrator’s capability to output as SVG for many years. But being a designer for the web, I’ve never really had a use for the format. Now that the day of the SVG is upon us, I went ahead and successfully got the Grunticon build process working using the free Ballicons full color SVG icon set. The reason I built this boilerplate was to ensure that on my next project, I’ll have the desired flexibility of SVG with PNG fallback automated in the build process. I also made a pen to show the output. BalliconsGrunticon
http://codepen.io/peterdillon/pen/dGMLNp
List of style-able SVG attributes and SVG 2
Remove and reduce colors to grayscale and black and whites if possible. Also printing gray’s can reduce the amount of black ink needed – so that’s a bonus if you want to really be nice. Add styling if you want the URLs to print out:
@media print{
a:after{content:" (" attr(href) ") ";
font-size:0.8em;
font-weight:normal;
}
Recently while building an application for Progressive Insurance it was expected that a user would be able to print the results of their schedule sorting. The requirements weren’t too challenging, the application opened a new window with table data that called a separate stylesheet.
Here is a codepen:
Advantages of SASS/LESS: Use of variables, mixins, nesting, looping, partials and more.
Advantages POSTCSS: Use of future syntax. Ability to select only the plugins you need for a particular project. Writing plain CSS and applying the plugin to output necessary syntax that suits your needs – which in turn allows for the ability to remove or update that plugin if at any time it is not useful anymore. In other words, POSTCSS offers a lot of flexibility AND all of the features SASS/LESS offer. Versions of POSTCSS have been developed for both Grunt and Gulp.
Disadvantage POSTCSS: Keeping track of plugins for older projects could get hairy, though you have a
package.json
to reference.Disdvantages of SASS/LESS: They are monolithic, and you need to learn a new language. I found this succinct comment:
Post-processors have to be implicit to silently improve CSS (prefixes, fallbacks, etc.) and pre-processors have to be explicit (use its own language) to generate CSS. (Ref – comment #1)
I’ve been nothing but impressed and content with the Compass/Sass workflow I’ve been using. Then when I began teaching myself Grunt, I was introduced to POSTCSS and I’ve been just as impressed and pleased to get on board. Maybe I’m too easy.
Okay this is a very contentious subject. Firefox and Opera, though at work on the issue, have an issue called FOUT “Flash Of Unstyled Text” The designer in me want’s every font choice there is. The developer and user in me says “I am only concerned with speed. I could not care less about that special font.” Let me put it this way, I land on both sides here. They are really easy to implement, but given that our devices are smaller and connections are not always reliable, you really need to consider your audience. If you want to squeeze people out that are on shaky connections – you better have a really good reason for it. Or you cold assume your audience always is in the toughest situation possible and design for that.
It matches from right to left for computing efficiency. Searching up the descendant chain stops when a match is found. If you went down, the renderer would have to say “okay matched
.a { }
, now is there a .a .b { }
match and continue downward.
Pseudo element use has been described in a previous question as a more semantic float ‘clearfix’ solution. They can be used as extra styling nodes as well. They could be thought of as ‘free markup objects’ that you don’t have to markup. I have used it for some iconography placeholder for prototyping. CSS-Tricks again comes through with a thorough post on all the wonderful things pseudo elements can achieve.
The box model is how browsers by default add border and padding sizes to elements with a specified width. To overcome this problem the short answer is:
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
Which gives you the flexibility to say “Everything should be box-sizing: border-box
but if I set this somewhere to box-sizing: content-box
, there is a good reason and I would like the descendants to keep that style.” Here is my pen:
{ box-sizing: border-box; }
do? What are its advantages?This is explained above.
I remembered these: block, inline, inline-block, none.
So I went and looked in up on MDN – Quickly I remembered “Oh yeah, all those table ones…” but I had no idea there was this many:
display: contents;
display: list-item;
display: inline-list-item;
display: table;
display: inline-table;
display: table-cell;
display: table-column;
display: table-column-group;
display: table-footer-group;
display: table-header-group;
display: table-row;
display: table-row-group;
display: flex;
display: inline-flex;
display: grid;
display: inline-grid;
display: ruby;
display: ruby-base;
display: ruby-text;
display: ruby-base-container;
display: ruby-text-container ;
display: run-in;
/* Global values */
display: inherit;
display: initial;
display: unset;
So, what is a ‘ruby’ display property? ruby
annotations are for showing pronunciation of East Asian characters. I made a pen exploring the magic of ruby
.
Elements with display:inline-block elements are like display:inline elements, but they can have a width and height. Sounds simple, but these guys can push each other around forming some quite unexpected and ugly results.
Static: is the default state. Elements stay in the flow of the document.
Relative: The position measurements will be relative to it’s containing div. Also stays in the document flow.
Fixed: Taken out of the document flow, position is relative to the window.
Absolute: Positions elements exactly relative to it’s parent. Without a parent it would act as fixed would.
How can you use this system to your advantage?
Priority
1. User agent declarations
2. User declarations
3. Author declarations
4. Author !important declarations
5. User !important declarations.
You can use cascading to your advantage by doing something as simple as this. You are now set up for flexible, web-safe, font variety for much of your blog:
body { font-size:100%; line-height:1.125em; }
h1 { font: 1.5em Georgia; }
p { font: 1em Palatino; }
I feel like I’ve been doing this so long, that it’s hard to put into words. It’s just understood. That said, we have all run into a “wtf” moment when you really need to dig into devtools to see why a thing is doing what you think it shouldn’t.
I just wanted to add one more part to this question. How is the CSS inheritance calculated?
Specified value: The user agent determines whether the value of the property comes from a style sheet, is inherited or should take its initial value.
Computed value: The specified value is resolved to a computed value and exists even when a property doesn’t apply. The document doesn’t have to be laid out for the computed value to be determined.
Used value: The used value takes the computed value and resolves any dependencies that can only be calculated after the document has been laid out (like percentages).
Actual value: This is the value used for the final rendering, after any approximations have been applied (for example, converting a decimal to an integer). Ref: Smashing Mag
I’ve been satisfied with the ease of use of all the frameworks I alluded to earlier. Typically writing css for large proprietary systems I’ve often started from scratch.
Not that much, I’m still wrapping my head around a lot of it but I recently (slowly and with a lot of attention) went through the flexboxfroggy.com game application and found it was really helpful in acquainting myself with many of the most used layout controls. Of course as usage and acceptance grows – I will be getting back to give more thoughtful response to this question.
Responsive uses media queries to adjust page layout, font size and more to customize a view for a user based on the size of their viewport. Adaptive is doing UA sniffing to adjust (possibly using media queries) the design, or the content delivered – based on their device and/or version of OS and browsers.
While SVG can cover all of your vector need by scaling beautifully – the responsive image battle (which includes retina) rages on. The picture element seems to be the winner and the syntax will look like this:
// But a real world situation for a fashionable site that
// wants to deliver the cutting edge image formate (webP) but has strict
// requirements to deliver the perfect size - will look more like this:
So all in all, it’s pretty hairy. There is lots of markup and future maintenance – but I admit it is the best solution I have seen so far and I appreciate all the effort that has been put into it.
Translate puts the element on a new compositing layer which gives the browser a hint that this particular piece will be changing (which includes standing still:
position: fixed;
.) Furthermore, when ‘trbl’ absolute position are used and animated there is large hit on performance due to paint time. translate() puts the animation into GPU and no paint calculations are calculated at all.JS Questions:
A common way I have used it is when I want find the item that is clicked on in a list – you add an event listener to the parent object. Then use the .target to reference the child object that emitted the event and react to it.
// HTML
- Item 1
- Item 2
//JS document.getElementById("parent-ul").addEventListener("click", function(e) { if(e.target) { console.log("Clicked on: ", e.target.id); } });
‘this’ is a property inside a function or object that is a reference to itself. But ‘this’ can change depending on it’s execution context – e.g. like a function inside another function, that’s inside an object – attaches itself back to the global object. Some feel this is a bug. Though it can be avoided by setting the ‘var self = this;’ pattern, and just refer to the self var. In ES6 the
let
keyword will also fix this issue.
var c = {
name: "c obj",
log: function() {
console.log(this); // Logs as 'Object' with name, etc
this.name = "Updated c obj";
console.log(this); // METHODS 'mutate' the object that I am contained in
var setname = function(newname){
this.name = newname; // This ODDLY attaches back to the WINDOW object - JS bug?
}
setname("Updated c once more!");
console.log(this); // Output: "Updated c obj" again due to bug
console.log(window.name); // Output: "Updated once more!"
}
}
c.log();
//Rewritten to reference correct this
var d = {
name: "d obj",
log: function() {
// To avoid the bug, we can set the this to self
// as the first line of the object method and reference that instead
var self = this;
console.log(self);
self.name = "Updated d obj";
console.log(self);
var setname = function(newname){
self.name = newname;
}
setname("Updated d once more!");
console.log(self);
}
}
d.log();
It is an easy way to give methods to many objects at once. A practical example would be:
function Person(fn, ln) {
this.fn = fn;
this.ln = ln;
}
var peter = new Person("Peter", "Dillon");
Person.prototype.getFullName = function() {
return this.fn + " " + this.ln;
}
console.log(peter.getFullName());
Rather than wasting memory space attaching the method to every instance of Person()
, now anytime an instance of Person()
needs that method they can just call the prototype method.
Because there is no containing parenthesis to alert the compiler that this is to be invoked.
What needs to be changed to properly make it an IIFE?
(function foo(){ }());
null is an object, undefined means it is declared but has no value, undeclared means it is trying to be referenced before it’s existence.
typeOf, ===, or == null (Ref)
The concept of a closure is that variables are only available within the context of the function in which they are created. You can use closures to mimic “private” method that keeps a variable unexposed, but then use a return statement to give the scope outside access to only what you want it to have.
var Module = (function() {
var privateMethod = function(num) {
var num;
num = num;
alert(num);
};
return {
func_1: function() { console.log("func 1"); },
func_2: function() { console.log("func 2"); },
publicMethod: function(num) {
privateMethod(num);
}
}
})();
Module.func_1();
Module.func_2();
Module.publicMethod(5);
Module.privateMethod(2);
// Output of above: Uncaught TypeError: Module.privateMethod is not a function
// Inaccessible - it's private!
As a callback and ways to implement private methods. When they are declared inline they can access variables in the parent scopes.
Native objects:
Object
(constructor), Date
, Math
, parseInt
, eval
, string methods like indexOf
and replace
, array methods, …Host objects: (assuming browser environment):
window
, document
, location
, history
, XMLHttpRequest
, setTimeout
, getElementsByTagName
, querySelectorAll
, .
function Person(){} // Declaration
var person = Person() // Declaration and assignment to ‘person’ var
var person = new Person() // ‘new’ is an operator that creates an empty object that invokes the Person function – and changes the ‘this’ variable which now points at the empty object (ONLY if the original function doesn’t return anything!) Using ‘new’ is a way to use a function to create an object – this is called a ‘function constructor.’
.apply takes parameters as an array – .call takes comma separated parameters.
This is a way to add a function or method up the chain so that is is available to all members who share the same Prototype.
When you want some plain html text to appear in the DOM.
Feature detection is using modernizr (or similar product) to detect the front-end web technologies (e.g. localStorage or css property) your browser supports.
The UA String gives you the rendering engine version, the OS and the device.
Feature inference is…
Asynchronous Javascript and XML. Is a way to send and retrieve data without a page refresh.
$.ajax({
url: 'http://your-app.com/api/news/today',
dataType: 'JSONp',
success: function(data, status) {
$.each(data, function(key, value){
//handle the data
});
},
error: function() {
//handle the error
}
}
You would use JS to inject a script tag into your html document – which has a src url that the browser makes an HTTP GET request to. The P is referred to “padding” which is a function that contains the JSON data. It is supposed to be a work around for cross domain ajax scripting
Hoisting describes the way in which the JavaScript interpreter declares variables at the top of the function it is contained in (the current scope.) And to clarify – declared not initialed (assigned) a value. This results in some variables being accessible even though they are not yet physically declared in the code. Common practice in JS is to always declare your vars at the top of your scope to avoid confusion.
Event bubbling is the way an event (such as click) that is nested in html elements actually triggers an event on all of it’s parent elements as well as itself. You can ‘capture’ a bubbling event on any of the parent elements. To stop the bubbling effect you can use
event.stopPropagation()
Properties are in the DOM and can be manipulated. Attributes are in the HTML and do not change – even if it was edited by a script:
If an element has a default value, the attribute shows the default value even if the value has changed (Ref)
$('input').prop('value', '456user');
$('input').prop('value'); // returns "456user"
$('input').attr('value'); // returns "user123"
In the future, if a browser decides to implement its own version of your method, your method might get overridden (silently) in the browser’s implementation. Ref:
The
ready
event occurs after the HTML document has been loaded, while the onload
event occurs later, when all content (e.g. images) also has been loaded.
The onload
event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready
event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn’t have to wait for all content to load.
window.onload
is the built-in Javascript event, but as its implementation had subtle quirks across browsers (FF/IE6/IE8/Opera), jQuery provides document.ready
, which abstracts those away, and fires as soon as the page’s DOM is ready (doesn’t wait for images etc.).
$(document).ready
(note that it’s not document.ready
, which is undefined) is a jQuery function, wrapping and providing consistency to the following events:
document.ondomcontentready
/ document.ondomcontentloaded
– a newish event which fires when the document’s DOM is loaded (which may be some time before the images etc. are loaded); again, slightly different in IE and in rest of the world
and window.onload
(which is implemented even in old browsers), which fires when the entire page loads (images, styles, etc.)
Double equals returns true if the operands are equal and may perform a type conversion when comparing two things. Triple equals compares the object type and operands are equal.
You cannot load assets from another domain from within JS code.
duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]
function duplicate(arr) {
arr = arr.concat(arr);
console.log(arr)
}
duplicate([1,2,3,4,5]);
Ternary means three. In terms of JS, it refers to shortcut expressions that perform three functions: condition, if true, if false. The syntax is:
condition ? true : false;
"use strict";
? What are the advantages and disadvantages to using it?Strict has many features, some useful ones are: stops global vars from being created and it turns mistakes (like mistypes) into errors.
for (var i = 0; i < 100; i++) {
if (!(i % 3) && !(i % 5)) { console.log( i + " FizzBuzz") }
else if (!(i % 3)) { console.log( i + " Fizz") }
else if (!(i % 5)) { console.log( i + " Buzz") }
else { console.log(i) }
};
Too avoid polluting the global namespace with variables that may crash into each other and be very difficult to debug.
Do you know any alternatives, and why would you use those?
I’ve used promises only in angular, for doing $http calls and use the .then as a cleaner way (by avoiding extensive nesting) to handle success and errors.
PRO: 1) Cleaner handling and chaining of methods. 2) Events can perform synchronously and send their result as it becomes ready.
CON: 1) Once you start a promise chain – you cannot exit out of it. 2) Callbacks need to be nested and can be difficult to debug.
You can use features that are not yet implemented.
devtools, jshint, jslint, track.js.
forEach()
is great for iterating over arrays – which are actually interpreted as objects by the compiler.
// Simple forEach
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element);
}
[2, 5, , 9].forEach(logArrayElements);
// Output:
// a[0] = 2
// a[1] = 5
// a[3] = 9
// -----------------------------------
// hasOwnProperty()
var o = {
name: "my name",
date: "today",
myFunc: function() { log(name + " " + date) }
}
for (prop in o) {
if (o.hasOwnProperty(prop)) {
console.log(prop + ": " + o[prop])
}
}
// Output:
// name: my name
// date: today
// myFunc: function () { log(name + " " + date) }
// -----------------------------------
// Combo
var myObj = { name : "Jim", age : 32, title : "Mr." }
Object.getOwnPropertyNames(myObj).forEach(function(val, idx, array) {
console.log(val + ' -> ' + myObj[val]);
});
// Output:
// name -> Jim
// age -> 32
// title -> Mr.
Mutable can have their properties changed. Immutable objects cannot be changed. It means the memory space once assigned cannot be changed.
Numbers and strings. Once it is instantiated, you cannot change it. You can reassign a new value to the original object – which is basically issuing a new memory space.
Object.freeze();
(reference)
JavaScript runtimes contain a message queue which stores a list of messages to be processed and their associated callback functions. These messages are queued in response to external events (such as a mouse being clicked or receiving the response to an HTTP request) given a callback function has been provided. If, for example a user were to click a button and no callback function was provided – no message would have been enqueued.
TODO: REF: MDN
Testing Questions:
TODO:
Jasmine
TODO:
To help maintain a standard within your team, so code is easier to read between members.
Performance Questions:
devtools has a lot of statistics to analyze, and if you can, run your site through web page test
Avoid fixed position elements, though soon the CSS property
will-change:transform
will hint the browser to these elements and reduce the jank.
STYLE CALCULATIONS: The browser matches each style rule to their elements by class and id names and applies the rules.
LAYOUT: Is when a browser calculates how much space is needed to apply the matched CSS rules.
PAINTING: Is when the browser draws text, color, images, border and shadows – essentially every visual element you see on the screen which can be spread across “layers.”
COMPOSITING: Is when the browser draws these blocks onto the screen, accounting for layer order.
Screen refresh ideally happens at 60fps (frames per second.) When an animation or scroll is happening, the screen tried to put up 1 picture per frame. Each of those frames has a budget of just over 16ms (1 second / 60 = 16.66ms) In reality, however, the browser has housekeeping work to do, so all of your work needs to be completed inside 10ms. (reference)
Network Questions:
This is a technique called “domain sharding” which takes advantage of a browsers ability to download multiple files (6) from each single domain at a time. So spreading assets across multiple domains (such as CDN’s) can give a performance boost by downloading many assets synchornously.
What happens and why it’s so slow:
DNS lookup, Socket Connect (TCP Handshake,) HTTP Request(s), Content Download (begin slow-start.) I’ve also written about it here.
Bandwidth (can always be increased, so not so important) This is how much data we can transfer at once, i.e. in one packet, from the source to the destination. We measure this in KBPS, MBPS or even GBPS if you have lots of money.
Latency (can change, but relies on physical network restraints) This is how long a packet takes to travel from the source to the destination. This is limited by the laws of physics. An electron can only travel at 1 speed on a copper wire. Increasing bandwidth has no affect on this. A photon on a fibre link can only travel at the speed of light. Even if we could increase this speed, Einstein tells us that this would negatively affect the latency! Finally, devices that process the data at various hops, e.g. routers, switches and firewalls, also add to latency. So, the further apart a client and server are, the longer a transmission takes. Adding in more network devices, e.g. transmissions between different ISP’s, worsens this.
Aidan Finn
HTTP Actions
- Do Not Track
- Cache-Control
- Transfer-Encoding
- ETag
- X-Frame-Options
- What are HTTP actions? List all HTTP actions that you know, and explain them.
Coding Questions:
Rather than run, copy, paste – I will try to explain why each results in the way it does.
var foo = 10 + '20';
ANSWER: 1020 – As a result of type coersion, the compiler sees a string last and says okay make that first one a string too. Another example: boolean == integer
the boolean operand will be converted to an integer: false becomes 0, true becomes 1. Then the two values are compared.
add(2, 5); // 7
add(2)(5); // 7
Two make line 2 work: Create a function that takes the params and adds them in a nested IFFE with a return. But to make line 1 work you have to do a check to see b is defined, if not you invoke the IFFE with the second parameter. ANSWER:
function add(a,b){
var d = function(b) { return a + b; };
if(typeof b == 'undefined') {
return d;
} else {
return d(b);
}
}
console.log(add(2)(3)); // 5
console.log(add(2,3)); // 5
"i'm a lasagna hog".split("").reverse().join("");
It takes the string and returns it in reverse palindrome style – includes the spaces. “goh angasal a m’i”
(window.foo || (window.foo = "bar"));
This assigns the string “bar” to a global (window) variable named foo. The initial window.foo ||
does nothing.
I will answer in the code for clarity.
var foo = "Hello";
(function() {
var bar = " World";
alert(foo + bar); // Output: Hello World
})();
alert(foo + bar); // Uncaught ReferenceError: bar is not defined
var foo = [];
foo.push(1);
foo.push(2);
.length
starts from 1 (not 0) so output = 2.
var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};
undefined
– the prop foo.x is never created anywhere.
console.log('one');
setTimeout(function() {
console.log('two');
}, 0);
console.log('three');
Even though setTimeout is set to 0 – it gets pushed to the end of the line in the callstack. In testing I discovered that all of the following asynchronous IFFE’s were also processed before the setTimeout.
Fun Questions:
Progressive Insurance Schedule Ranking System
They help me do stuff.
BeerSnob – Coming soon to an appstore near you! It will be an AngularJS, Ionic, PostCSS coding pleasuresphere.
That they are now one of the biggest (loudest, to be more accurate) proponents of “following standards.” They have evangelism teams now that have made rounds on the podcasts touting IE (11+) as having some of the highest percentage of standard specs implemented.
My Additional Questions:
window.requestAnimationFrame
work?requestAnimationFrame
is a recent feature added to browsers that asks the current window if it is active or visible. It has a callback function that will run your animation when the current window is active, matching your browser’s frames-per-second ratio and the result is smoother animation. The benefits can be less battery usage, and preventing a memory sensitive looping animation from draining your CPU. You can see it work in the pen below, by tabbing away, and when you come back the animation will be at the frame you left it.- setTimeout doesn’t take into account what else is happening in the browser. The page could be hidden behind a tab, hogging your CPU when it doesn’t need to, or the animation itself could have been scrolled off the page making the update call again unnecessary. Chrome does throttle setInterval and setTimeout to 1fps in hidden tabs, but this isn’t to be relied upon for all browsers.
- setTimeout only updates the screen when it wants to, not when the computer is able to. That means your browser has to juggle redrawing the animation while redrawing the whole screen, and if your animation frame rate is not synchronized with the redrawing of your screen, it could take up more processing power. That means higher CPU usage and your computer’s fan kicking in, or draining the battery on your mobile device. Nicolas Zakas explains the impact timer resolution has on animation.
el.onclick = function() {}
el.addEventListener('click', start , false);
Inline events (line 1) may only have one inline event assigned. Inline events are stored as an attribute/property of the element, meaning that it will be overwritten by a second onclick
event. addEventListener
can have an unlimited succession of events fired.