SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Downloaden Sie, um offline zu lesen
JavaScript
Best Practices


Sang Shin
Java Technology Architect
Sun Microsystems, Inc.
sang.shin@sun.com
www.javapassion.com
Disclaimer & Acknowledgments
• Even though Sang Shin is a full-time employee of
  Sun Microsystems, the contents here are created as
  his own personal endeavor and thus does not
  necessarily reflect any official stance of Sun
  Microsystems on any particular technology
• Acknowledgments
  > The contents of this presentation was created from
    “JavaScript recommendations for AJAX component writers”
    written by Greg Murray
     > https://blueprints.dev.java.net/bpcatalog/conventions/javascript-
       recommendations.html

                                                                           2
Topics

•   Use Object-oriented JavaScript
•   Use Object hierarchy
•   Use the prototype property
•   Write reusable JavaScript code
•   Use Object literals as function parameters
•   Load JavaScript on demand
•   Clean separation of content, CSS, and JavaScript
•   Reduce the size of JavaScript file
                                                       3
Use Object Oriented
JavaScript
Use Object Oriented JavaScript

• Provides better reusability of the code
• Enables your objects to be better organized
• Allow for dynamic loading of objects




                                                5
Example: Cart Object in JavaScript
// The Cart object above provides basic support for maintaining
     //
// an internal array of Item objects
function Cart() {
  this.items = [];
}
function Item (id,name,desc,price) {
    this.id = id;
    this.name = name;
    this.desc = desc;
    this.price = price;
}
// Create an instance of the Cart and add items
var cart = new Cart();
cart.items.push(new Item(quot;id-1quot;,quot;Paperquot;,quot;something you write onquot;,5));
cart.items.push(new Item(quot;id-2quot;,quot;Penquot;, quot;Something you write withquot;,3));
var total = 0;
for (var l = 0; l < cart.items.length; l++) {
   total = total + cart.items[l].price;
}
                                                                         6
Example: Comparable Java Code
public class Cart {
  private ArrayList items = new ArrayList();
  public ArrayList getItems() {
     return items;
  }
}
public class Item {
  private String id; private String name; private String desc; private double price;
    public Item(String id, String name, String desc, double price) {
      this.id = id;
      this.name = name;
      this.desc = desc;
      this.price = price;
    }
    public String getId() {return id;}
    public String getName() {return name;}
    public String getDesc() {return desc;}
    public float getPrice() {return price;}
}
                                                                                       7
Use Object Hierarchy
Use Object Hierarchies to Organize
JavaScript Objects to Avoid Name Collision

• In JavaScript there is the potential for object names
  to collide
  > In Java language, package names are used to prevent
    naming collisions
• JavaScript does not provide package names like
  Java however you can
  > When writing components use objects and object hierarchies
    to organize related objects and prevent naming collision



                                                                 9
Example: Create a top level object BLUEPRINTS which
acts in a sense like a namespace for related objects
// create the base BLUEPRINTS object if it does not exist.
if (!BLUEPRINTS) {
    var BLUEPRINTS = new Object();
}
// define Cart under BLUEPRINTS
BLUEPRINTS.Cart = function () {
   this.items = [];
    this.addItem = function(id, qty) {
       this.items.push(new Item(id, qty));
    }
    function Item (id, qty) {
       this.id = id;
       this.qty = qty;
    }
}
// create an instance of the cart and add an item
var cart = new BLUEPRINTS.Cart();
cart.addItem(quot;id-1quot;, 5);
cart.addItem(quot;id-2quot;, 10);                                    10
Use the prototype
property
Use the prototype property
• Use it to define shared behavior and to extend
  objects
• The prototype property is a language feature of
  JavaScript
  > The property is available on all objects




                                                    12
Example: Usage of “prototype” property

function Cart() {
         this.items = [ ];
}
function Item (id,name,desc,price)) {
         this.id = id;
         this.name = name;
         this.desc = desc;
         this.price = price;
}
// SmartCart extends the Cart object inheriting its properties and adds a total property
function SmartCart() {
         this.total = 0;
}
SmartCart.prototype = new Cart();


                                                                                           13
Example: Usage of “prototype” property
// Declare a shared addItem and calcualteTotal function and adds them
// as a property of the SmartCart prototype member.
Cart.prototype.addItem = function(id,name,desc,price) {
         this.items.push(new Item(id,name,desc,price));
}
Cart.prototype.calculateTotal = function() {
         for (var l=0; l < this.items.length; l++) {
               this.total = this.total + this.items[l].price;
         }
         return this.total;
}
// Create an instance of a Cart and add an item
var cart = new SmartCart();
cart.addItem(quot;id-1quot;,quot;Paperquot;, quot;Something you write onquot;, 5);
cart.addItem(quot;id-1quot;,quot;Penquot;, quot;Soemthing you write withquot;, 3);
alert(quot;total is: quot; + cart.calculateTotal());

                                                                        14
Write reusable JavaScript
Write reusable JavaScript

• JavaScript should not be tied to a specific
  component unless absolutely necessary
• Consider not hard coding data in your functions that
  can be parameterized




                                                         16
Example: Reusable JavaScript function
// The doSearch() function in this example can be reused because it is
// parameterized with the String id of the element, service URL, and the <div>
// to update. This script could later be used in another page or application
<script type=quot;text/javascriptquot;>
          doSearch(serviceURL, srcElement, targetDiv) {
               var targetElement = document.getElementById(srcElement);
               var targetDivElement = document.getElementById(targetDiv);
               // get completions based on serviceURL and srcElement.value
               // update the contents of the targetDiv element
          }
</script>
<form onsubmit=quot;return false;quot;>
        Name: <input type=quot;inputquot; id=quot;ac_1quot; autocomplete=quot;falsequot;
                   onkeyup=quot;doSearch('nameSearch','ac_1','div_1')quot;>
        City: <input type=quot;inputquot; id=quot;ac_2quot; autocomplete=quot;falsequot;
                   onkeyup=quot;doSearch('citySearch','ac_2','div_2')quot;>
        <input type=quot;buttonquot; value=quot;Submitquot;>
</form>
<div class=quot;completequot; id=quot;div_1quot;></div>
<div class=quot;completequot; id=quot;div_2quot;></div>
                                                                                 17
Use object literals as
flexible function
parameters
Object Literals

• Object literals are objects defined using braces ({})
  that contain a set of comma separated key value
  pairs much like a map in Java
• Example
  > {key1: quot;stringValuequot;, key2: 2, key3: ['blue','green','yellow']}
• Object literals are very handy in that they can be
  used as arguments to a function
• Object literals should not be confused with JSON
  which has similar syntax

                                                                      19
Example: Usage of Object Literals as
parameters
function doSearch(serviceURL, srcElement, targetDiv) {
        // Create object literal
        var params = {service: serviceURL, method: quot;getquot;, type: quot;text/xmlquot;};
        // Pass it as a parameter
        makeAJAXCall(params);
}
// This function does not need to change
function makeAJAXCall(params) {
          var serviceURL = params.service;
          ...
 }




                                                                               20
Example: Usage of Object Literals as
parameters - Anonymous Object Literals
function doSearch() {
         makeAJAXCall({serviceURL: quot;fooquot;,
                       method: quot;getquot;,
                       type: quot;text/xmlquot;,
                       callback: function(){alert('call done');}
                       });
 }
function makeAJAXCall(params) {
         var req = // getAJAX request;
         req.open(params.serviceURL, params.method, true);
         req.onreadystatechange = params.callback;
         ...
}




                                                                   21
Load JavaScript
on Demand
Load JavaScript On Demand

• If you have a large library or set of libraries you
  don't need to load everything when a page is
  loaded
• JavaScript may be loaded dynamically at runtime
  using a library such as JSAN or done manually
  by using AJAX to load JavaScript code and
  calling eval() on the JavaScript



                                                        23
Example: Load JavaScript On Demand

// Suppose the following is captured as cart.js file
function Cart () {
     this.items = [ ];
     this.checkout = function() {
                                 // checkout logic
                                 }
 }
---------------------------------------------------------------------
// get cart.js using an AJAX request
eval(javascriptText);
var cart = new Cart();
// add items to the cart
cart.checkout();



                                                                        24
Clean separation of
Content, CSS, and
JavaScript
Separation of content, CSS, and
JavaScript
• A rich web application user interface is made up of
  > content (HTML/XHTML)
  > styles (CSS)
  > JavaScript
• Separating the CSS styles from the JavaScript is a
  practice which will make your code more
  manageable, easier to read, and easier to customize
• Place CSS and JavaScript code in separate files
• Optimize the bandwidth usage by having CSS and
  JavaScript file loaded only once
                                                        26
Example: Bad Practice

<style>
#Styles
</style>
<script type=quot;text/javascriptquot;>
// JavaScript logic
<script>
<body>The quick brown fox...</body>




                                      27
Example: Good Practice

<link rel=quot;stylesheetquot; type=quot;text/cssquot; href=quot;cart.cssquot;>
<script type=quot;text/javascriptquot; src=quot;cart.jsquot;>
<body>The quick brown fox...</body>




                                                          28
Reduce the size of
JavaScript file
Reduce the size of JavaScript file

• Remove the white spaces and shortening the names
  of variables and functions in a file
• While in development mode keep your scripts
  readable so that they may be debugged easier
• Consider compressing your JavaScript resources
  when you deploy your application
• If you use a 3rd party JavaScript library use the
  compressed version if one is provided.
  > Example compression tool: ShrinkSafe

                                                  30
JavaScript
Best Practices


Sang Shin
Java Technology Architect
Sun Microsystems, Inc.
sang.shin@sun.com
www.javapassion.com

Weitere ähnliche Inhalte

Was ist angesagt?

Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScriptSimon Willison
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesDoris Chen
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptzand3rs
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 

Was ist angesagt? (20)

Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 

Ähnlich wie Java Script Best Practices

Professional JavaScript Development - Creating Reusable Code
Professional JavaScript Development -  Creating Reusable CodeProfessional JavaScript Development -  Creating Reusable Code
Professional JavaScript Development - Creating Reusable CodeWildan Maulana
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templatingbcruhl
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2borkweb
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsZohar Arad
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript LiteracyDavid Jacobs
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorialDoeun KOCH
 
Java script object model
Java script object modelJava script object model
Java script object modelJames Hsieh
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Scriptccherubino
 
Scala, XML and GAE
Scala, XML and GAEScala, XML and GAE
Scala, XML and GAEmarkryall
 

Ähnlich wie Java Script Best Practices (20)

OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
 
Professional JavaScript Development - Creating Reusable Code
Professional JavaScript Development -  Creating Reusable CodeProfessional JavaScript Development -  Creating Reusable Code
Professional JavaScript Development - Creating Reusable Code
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templating
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
WD programs descriptions.docx
WD programs descriptions.docxWD programs descriptions.docx
WD programs descriptions.docx
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
Java script object model
Java script object modelJava script object model
Java script object model
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Script
 
Scala, XML and GAE
Scala, XML and GAEScala, XML and GAE
Scala, XML and GAE
 

Kürzlich hochgeladen

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 

Kürzlich hochgeladen (20)

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 

Java Script Best Practices

  • 1. JavaScript Best Practices Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com
  • 2. Disclaimer & Acknowledgments • Even though Sang Shin is a full-time employee of Sun Microsystems, the contents here are created as his own personal endeavor and thus does not necessarily reflect any official stance of Sun Microsystems on any particular technology • Acknowledgments > The contents of this presentation was created from “JavaScript recommendations for AJAX component writers” written by Greg Murray > https://blueprints.dev.java.net/bpcatalog/conventions/javascript- recommendations.html 2
  • 3. Topics • Use Object-oriented JavaScript • Use Object hierarchy • Use the prototype property • Write reusable JavaScript code • Use Object literals as function parameters • Load JavaScript on demand • Clean separation of content, CSS, and JavaScript • Reduce the size of JavaScript file 3
  • 5. Use Object Oriented JavaScript • Provides better reusability of the code • Enables your objects to be better organized • Allow for dynamic loading of objects 5
  • 6. Example: Cart Object in JavaScript // The Cart object above provides basic support for maintaining // // an internal array of Item objects function Cart() { this.items = []; } function Item (id,name,desc,price) { this.id = id; this.name = name; this.desc = desc; this.price = price; } // Create an instance of the Cart and add items var cart = new Cart(); cart.items.push(new Item(quot;id-1quot;,quot;Paperquot;,quot;something you write onquot;,5)); cart.items.push(new Item(quot;id-2quot;,quot;Penquot;, quot;Something you write withquot;,3)); var total = 0; for (var l = 0; l < cart.items.length; l++) { total = total + cart.items[l].price; } 6
  • 7. Example: Comparable Java Code public class Cart { private ArrayList items = new ArrayList(); public ArrayList getItems() { return items; } } public class Item { private String id; private String name; private String desc; private double price; public Item(String id, String name, String desc, double price) { this.id = id; this.name = name; this.desc = desc; this.price = price; } public String getId() {return id;} public String getName() {return name;} public String getDesc() {return desc;} public float getPrice() {return price;} } 7
  • 9. Use Object Hierarchies to Organize JavaScript Objects to Avoid Name Collision • In JavaScript there is the potential for object names to collide > In Java language, package names are used to prevent naming collisions • JavaScript does not provide package names like Java however you can > When writing components use objects and object hierarchies to organize related objects and prevent naming collision 9
  • 10. Example: Create a top level object BLUEPRINTS which acts in a sense like a namespace for related objects // create the base BLUEPRINTS object if it does not exist. if (!BLUEPRINTS) { var BLUEPRINTS = new Object(); } // define Cart under BLUEPRINTS BLUEPRINTS.Cart = function () { this.items = []; this.addItem = function(id, qty) { this.items.push(new Item(id, qty)); } function Item (id, qty) { this.id = id; this.qty = qty; } } // create an instance of the cart and add an item var cart = new BLUEPRINTS.Cart(); cart.addItem(quot;id-1quot;, 5); cart.addItem(quot;id-2quot;, 10); 10
  • 12. Use the prototype property • Use it to define shared behavior and to extend objects • The prototype property is a language feature of JavaScript > The property is available on all objects 12
  • 13. Example: Usage of “prototype” property function Cart() { this.items = [ ]; } function Item (id,name,desc,price)) { this.id = id; this.name = name; this.desc = desc; this.price = price; } // SmartCart extends the Cart object inheriting its properties and adds a total property function SmartCart() { this.total = 0; } SmartCart.prototype = new Cart(); 13
  • 14. Example: Usage of “prototype” property // Declare a shared addItem and calcualteTotal function and adds them // as a property of the SmartCart prototype member. Cart.prototype.addItem = function(id,name,desc,price) { this.items.push(new Item(id,name,desc,price)); } Cart.prototype.calculateTotal = function() { for (var l=0; l < this.items.length; l++) { this.total = this.total + this.items[l].price; } return this.total; } // Create an instance of a Cart and add an item var cart = new SmartCart(); cart.addItem(quot;id-1quot;,quot;Paperquot;, quot;Something you write onquot;, 5); cart.addItem(quot;id-1quot;,quot;Penquot;, quot;Soemthing you write withquot;, 3); alert(quot;total is: quot; + cart.calculateTotal()); 14
  • 16. Write reusable JavaScript • JavaScript should not be tied to a specific component unless absolutely necessary • Consider not hard coding data in your functions that can be parameterized 16
  • 17. Example: Reusable JavaScript function // The doSearch() function in this example can be reused because it is // parameterized with the String id of the element, service URL, and the <div> // to update. This script could later be used in another page or application <script type=quot;text/javascriptquot;> doSearch(serviceURL, srcElement, targetDiv) { var targetElement = document.getElementById(srcElement); var targetDivElement = document.getElementById(targetDiv); // get completions based on serviceURL and srcElement.value // update the contents of the targetDiv element } </script> <form onsubmit=quot;return false;quot;> Name: <input type=quot;inputquot; id=quot;ac_1quot; autocomplete=quot;falsequot; onkeyup=quot;doSearch('nameSearch','ac_1','div_1')quot;> City: <input type=quot;inputquot; id=quot;ac_2quot; autocomplete=quot;falsequot; onkeyup=quot;doSearch('citySearch','ac_2','div_2')quot;> <input type=quot;buttonquot; value=quot;Submitquot;> </form> <div class=quot;completequot; id=quot;div_1quot;></div> <div class=quot;completequot; id=quot;div_2quot;></div> 17
  • 18. Use object literals as flexible function parameters
  • 19. Object Literals • Object literals are objects defined using braces ({}) that contain a set of comma separated key value pairs much like a map in Java • Example > {key1: quot;stringValuequot;, key2: 2, key3: ['blue','green','yellow']} • Object literals are very handy in that they can be used as arguments to a function • Object literals should not be confused with JSON which has similar syntax 19
  • 20. Example: Usage of Object Literals as parameters function doSearch(serviceURL, srcElement, targetDiv) { // Create object literal var params = {service: serviceURL, method: quot;getquot;, type: quot;text/xmlquot;}; // Pass it as a parameter makeAJAXCall(params); } // This function does not need to change function makeAJAXCall(params) { var serviceURL = params.service; ... } 20
  • 21. Example: Usage of Object Literals as parameters - Anonymous Object Literals function doSearch() { makeAJAXCall({serviceURL: quot;fooquot;, method: quot;getquot;, type: quot;text/xmlquot;, callback: function(){alert('call done');} }); } function makeAJAXCall(params) { var req = // getAJAX request; req.open(params.serviceURL, params.method, true); req.onreadystatechange = params.callback; ... } 21
  • 23. Load JavaScript On Demand • If you have a large library or set of libraries you don't need to load everything when a page is loaded • JavaScript may be loaded dynamically at runtime using a library such as JSAN or done manually by using AJAX to load JavaScript code and calling eval() on the JavaScript 23
  • 24. Example: Load JavaScript On Demand // Suppose the following is captured as cart.js file function Cart () { this.items = [ ]; this.checkout = function() { // checkout logic } } --------------------------------------------------------------------- // get cart.js using an AJAX request eval(javascriptText); var cart = new Cart(); // add items to the cart cart.checkout(); 24
  • 25. Clean separation of Content, CSS, and JavaScript
  • 26. Separation of content, CSS, and JavaScript • A rich web application user interface is made up of > content (HTML/XHTML) > styles (CSS) > JavaScript • Separating the CSS styles from the JavaScript is a practice which will make your code more manageable, easier to read, and easier to customize • Place CSS and JavaScript code in separate files • Optimize the bandwidth usage by having CSS and JavaScript file loaded only once 26
  • 27. Example: Bad Practice <style> #Styles </style> <script type=quot;text/javascriptquot;> // JavaScript logic <script> <body>The quick brown fox...</body> 27
  • 28. Example: Good Practice <link rel=quot;stylesheetquot; type=quot;text/cssquot; href=quot;cart.cssquot;> <script type=quot;text/javascriptquot; src=quot;cart.jsquot;> <body>The quick brown fox...</body> 28
  • 29. Reduce the size of JavaScript file
  • 30. Reduce the size of JavaScript file • Remove the white spaces and shortening the names of variables and functions in a file • While in development mode keep your scripts readable so that they may be debugged easier • Consider compressing your JavaScript resources when you deploy your application • If you use a 3rd party JavaScript library use the compressed version if one is provided. > Example compression tool: ShrinkSafe 30
  • 31. JavaScript Best Practices Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com www.javapassion.com