D3.js is a javascript library for manipulating DOM objects  based on data. we can create rich visualizations of data.

D3 provides a number of modules for helping us code many of thing that we need to create interactive data. Such as: Shapes, Scales, Layouts, Behaviors, Data-processing(JSON, CSV)

Simple case:

d3.select("body").selectAll("p")
.data([4, 8])
.enter().append("p")
.text(function(d) { return d + " squared is " + d*d + "!"; });

 
var jsonCircles = [
   {
    "x_axis": 30,
    "y_axis": 30,
    "radius": 20,
    "color" : "green"
   }, {
    "x_axis": 70,
    "y_axis": 70,
   "radius": 20,
   "color" : "purple"
  }];
var svgContainer = d3.select("body").append("svg")
                                    .attr("width", 200)
                                    .attr("height", 200);

var circles = svgContainer.selectAll("circle")
                          .data(jsonCircles)
                          .enter()
                          .append("circle");
Loading data from JSON file and using D3.js to visualization data

Loading data from JSON file and using D3.js to visualization data

The HTML DOM

HTML DOM

HTML DOM

 

HTML Form

Grouping Form Data with <fieldset>

The <fieldset> element groups related data in a form.

The <legend> element defines a caption for the <fieldset> element.

Example

<form action=”action_page.php”>
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type=”text” name=”firstname” value=”Mickey”><br>
Last name:<br>
<input type=”text” name=”lastname” value=”Mouse”><br><br>
<input type=”submit” value=”Submit”>
</fieldset>
</form>

 

Attribute Description
accept-charset Specifies the charset used in the submitted form (default: the page charset).
action Specifies an address (url) where to submit the form (default: the submitting page).
autocomplete Specifies if the browser should autocomplete the form (default: on).
enctype Specifies the encoding of the submitted data (default: is url-encoded).
method Specifies the HTTP method used when submitting the form (default: GET).
name Specifies a name used to identify the form (for DOM usage: document.forms.name).
novalidate Specifies that the browser should not validate the form.
target Specifies the target of the address in the action attribute (default: _self).

 

Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements

Method Description
element.innerHTML =  new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.setAttribute(attribute, value) Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element

Adding and Deleting Elements

Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(element) Replace an HTML element
document.write(text) Write into the HTML output stream

Adding Events Handlers

Method Description
document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event

<html>
<body>

<p id=”p1″>Hello World!</p>

<script>
document.getElementById(“p1”).innerHTML = “New text!”;
</script>

</body>
</html>

 

jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action()

  • A $ sign to define/access jQuery
  • A (selector) to “query (or find)” HTML elements
  • A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() – hides the current element.

$(“p”).hide() – hides all <p> elements.

$(“.test”).hide() – hides all elements with class=”test”.

$(“#test”).hide() – hides the element with id=”test”.

Mouse Events Keyboard Events Form Events Document/Window Events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload

JavaScript Data Types

JavaScript variables can hold many data types: numbers, strings, arrays, objects and more:

var length = 16;                               // Number
var lastName = “Johnson”;                      // String
var cars = [“Saab”, “Volvo”, “BMW”];           // Array

// var cars = new Array(“Saab”, “Volvo”, “BMW”);
var x = {firstName:”John”, lastName:”Doe”};    // Object

function name(parameter1, parameter2, parameter3) {
code to be executed
}

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById(“demo”).innerHTML = toCelsius(77);

 

 

 

 

 

 

 

 

Object Properties Methods

Auto object

Auto object

car.name = Fiatcar.model = 500

car.weight = 850kg

car.color = white

car.start()car.drive()

car.brake()

car.stop()

 

var person = {
firstName:”John”,
lastName:”Doe”,
age:50,
eyeColor:”blue”,

fullName : function() {

return this.firstName + ” ” + this.lastName;

}
};

 

Common HTML Events

Here is a list of some common HTML events:

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

<button onclick=”this.innerHTML=Date()”>The time is?</button>

 

Array Properties

Property Description
constructor Returns the function that created the Array object’s prototype
length Sets or returns the number of elements in an array
prototype Allows you to add properties and methods to an Array object

Array Methods

Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
copyWithin() Copies array elements within the array, to and from specified positions
every() Checks if every element in an array pass a test
fill() Fill the elements in an array with a static value
filter() Creates a new array with every element in an array that pass a test
find() Returns the value of the first element in an array that pass a test
findIndex() Returns the index of the first element in an array that pass a test
forEach() Calls a function for each array element
indexOf() Search the array for an element and returns its position
isArray() Checks whether an object is an array
join() Joins all elements of an array into a string
lastIndexOf() Search the array for an element, starting at the end, and returns its position
map() Creates a new array with the result of calling a function for each array element
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
reduce() Reduce the values of an array to a single value (going left-to-right)
reduceRight() Reduce the values of an array to a single value (going right-to-left)
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
some() Checks if any of the elements in an array pass a test
sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
unshift() Adds new elements to the beginning of an array, and returns the new length
valueOf() Returns the primitive value of an array

 

 

JavaScript Performance

Reduce Activity in Loops

Loops are often used in programming.

Each statement in a loop, including the for statement, is executed for each iteration of the loop.

Search for statements or assignments that can be placed outside the loop.

Bad Code:

for (i = 0; i < arr.length; i++) {

Better Code:

l = arr.length;
for (i = 0; i < l; i++)

 

Avoid Unnecessary Variables

Don’t create new variables if you don’t plan to save values.

Often you can replace code like this:

var fullName = firstName + ” ” + lastName;
document.getElementById(“demo”).innerHTML = fullName;

With this:

document.getElementById(“demo”).innerHTML = firstName + ” ” + lastName

 

The speed of a page is made up of both Front-end and Server-side components. GTmetrix assesses the front-end structure of your page to ensure that it is delivered as optimally as possible to your visitors, but an optimized server-side is also an important part of the equation in offering a fast and seamless site experience.

With PageSpeed and YSlow, it’s easy to put too much emphasis on the front-end and forget about the server-side. It’s important to remember that even though you may have high PageSpeed and YSlow scores, you could make your page even faster by optimizing your server-side.

 

What Makes up my Page Load Time?

When a request for a page is made, the Front-end and Server-side components both take a certain amount of time to complete their operations. Since their operations are essentially sequential, their cumulative time can be considered the total page load time.

Front End vs Back End

The front and back-end factors to site speed: A fast time is composed of both of these sides working in an optimal setup.

Even after you’ve optimized your Front-end, speed gains can still be achieved by optimizing the Server-side. This means optimizing the way the page is generated by your server.

A good indicator of your Server-side performance is the time it takes to generate the HTML page (page generation time). This is labeled as “Waiting” time on the first element in the waterfall graph (also known as the “time to first byte”). Generally, this time should be kept under one second (or as low as possible).


How Can I Make the Server-side Faster?

There are many causes to a slow server-side, but they can essentially be grouped into two categories:

  • Inefficient code or SQL
  • Bottlenecks/Slow Server

Since each site has a unique platform and setup, the solution to these issues is dependent on each site. One site might need to have their server-side code optimized, but another might just need a more powerful server. Budget constraints may also come into play, as optimizing server-side code for minor speed gains might be more affordable than upgrading servers for massive speed gains.

It’s best to truly understand your requirements before pursuing a server-side option path.


Solutions

The following optimizations are commonly used to improve server-side speed:

Code Optimization

Programming languages like PHP, Perl, Python, or ASP are usually teamed up with databases like MySQL, PostgreSQL, or Microsoft SQL Server to create software such as WordPress, Drupal, Magento and all sorts of custom platforms.

This software is usually fairly optimized out of the box, but there are often many customizations to the code or plugins that cause slow performance as a result of inefficient code or un-optimized database queries.

Code optimization involves analyzing the code and database queries and finding the spots where the code is inefficient and where database queries are slow. After finding these “hotspots,” it’s the job of a developer to fix those problems. For code this often involves finding a better algorithm or modifying the code to work around a bottleneck (ie. hard disk space or I/O, bandwidth, etc). For databases, this may involve adding indexes to speed up the query, rewriting the query or modifying the structure of the database.

Page Caching

Most websites today are dynamic, meaning that they pull from a database of information, insert the pulled data into templates, and then serve them to you. This happens every time somebody requests a page from the server, and the time it takes to perform this process is dependent on the efficiency of the code and the power of said servers.

Without Page Caching

No page caching

The server gets a request, queries the database for content, builds the page, and sends generated html back.

Since the server is handling thousands of requests for the same page, and is essentially “building” the same page every time, why not build the page once, and send that “pre-built” version to anybody that requests it? This is referred to as page caching.

With Page Caching

With page caching

If the server gets a request for page it has previously generated, it sends that version back immediately. That version is the “Cached” page.

Sending your users “cached” versions of pages is like giving them photocopies of a flyer. It’s much faster for you to give them photocopies than redrawing and writing the content each time somebody asks for one.

Page caching can be a very effective means of speeding up the generation of a page, but it also has its downsides:

  • Pages that require authentication can’t be cached (as they often contain user information on them).
  • Changes to pages don’t show up until the page cache has expired.

More Powerful Servers

Let’s define two popular terms in the hosting world:

  • Shared Hosting or Virtual Hosting: This means that including your website, the server hosts many websites. All these websites share its processing power and resources.
  • Dedicated Hosting: You are the only user on the server. The server’s processing power and resources are dedicated solely to your website(s).

The Issues With Shared Hosting

Shared servers

A Shared Server.

Shared hosting is the most affordable, and can be reliably used for starter sites or development purposes.

However, when an enterprise level site matures to the point where traffic is ramping up, a shared server cannot offer much in terms of speed enhancements.

How Dedicated Hosting Compares

Dedicated servers

A Dedicated Server.

Larger sites may require multiple dedicated servers (clusters) that play different roles (database querying, media serving, etc.) to generate a faster page load. These servers are built for performance, and so their specifications are quite powerful.

Dedicated servers are typically reserved for higher-traffic, resource intensive websites (you won’t need one for a small website about your cat) and are higher in cost than shared servers. They are a must, however, for enterprise-level websites and businesses where their website is mission-critical.


Results

In combination with a speedy front-end, optimizing your Server-side performance can yield amazing results for your page load time.

Generally, the page generation time for complex dynamic sites can be kept under 0.5 seconds.

Need help? We know optimization and we know it well. Finding the best solution to speed up your website isn’t always clear cut, but with 16 years of web experience, we can help you plan, develop, and implement a faster site experience for you and your users.