javascript - Offirmo-team/wiki GitHub Wiki

Voir aussi navigateur, typescript, appli web, node.js, express.js, AngularJS, primus, grunt, mocha/chai, serveur, backbone, babel, développement web...

Liens rapides

Introduction

Changements récents

Références

Meta

Blogs

Livres / cours

Tests

Advocacy

Feedback

Fun

History

Apprendre

See https://gist.github.com/Offirmo/fac3c3064b4c239f874e39bb8933a71c

TOSORT

Références

Sécurité

Libs

Histoire

Installation

node.js ou simple navigateur

Usage

Exécution

Voir node.js

page web

Voir aussi appli web

async-defer (source https://developers.google.com/web/fundamentals/primers/modules)

<!DOCTYPE html>
<html lang=en>
<head>
	<meta charset="utf-8">
	<title>JS base 2</title>
	<script src="http://ajax.googleapis.com/ajax/libs/xyz/1.9.1/xyz.js"></script>
</head>
<body>
	<p>Javascript enabled page</p>

	<script>
		console.log("hello world");
	</script>
	<script type="module" src="module.js"></script>
	<script type="module">
	  // or an inline script
	  import {helperMethod} from './providesHelperMethod.js';
	  helperMethod();
	</script>

	<noscript>Your browser either does not support JavaScript, or has it turned off.</noscript>

</body>
</html>

séquence d'exécution :

Priorités

modules

https://michelenasti.com/2019/06/24/typescript-why-so-complicated.html

Conception

TRÈS intéressant

Best practices

gestion d'erreur

http://blog.risingstack.com/node-js-best-practices-part-2/

  • Consistent Style
  • Enforce JSHint / JSCS Rules
  • JS over JSON for configuration
  • Dependency Injection

http://thenodeway.io/introduction/

  • Structure
    • Build Small Modules
    • Build Modules to Serve a Single Purpose
    • ... But Don't Get Carried Away
    • Complexity via Composition
  • Async
    • Leverage I/O, Avoid Heavy Computation
    • Invest in Clean Async
    • Return Early
    • Follow Standard Callback Patterns
    • Get Help With Control Flow
  • Community
    • Leverage the Ecosystem (or: There’s a Module for That)
    • Use the Best Tool for the Job
    • Write Modules for Others to Read
    • Build Modules for Others to Use
    • Embrace the Community

langage

Subtilités

this

Truth, Equality

strict

delete

http://perfectionkills.com/understanding-delete/

timers

http://blog.getify.com/on-the-nature-of-timers/

Erreurs

Objet très spécial

dangerous functions

  • sort must always be used with a sort function: [1, 10, 2].sort() -> [1, 10, 2]
  • parseInt must always be passed a base, and should never be used in map(parseInt)

questions d'entretien

crazy

getter setter

OO / héritage

Constructeur

var ShutdownAgent = function ShutdownAgent(options) {
	this.config = _.defaults({}, options, DEFAULT_CONFIG);
	this.shutdown_steps = [];
};

ShutdownAgent.prototype.start = function() {

};

Discussion

Héritage

function Derived() {
  // Call the parent constructor
  Parent.prototype.constructor.apply(this, arguments);
}
Derived.prototype = Object.create(Parent.prototype);
Derived.prototype.constructor = Derived;

Chaîne de prototypes :

Discussion

à trier

delete

http://blogs.codes-sources.com/cyril/archive/2008/01/26/javascript-mot-cle-delete-supprimer-propriete-objet-expando-attribute.aspx

modules

Utilisation de modules

Sources de modules

Chargeur de ressources

Spécialités

IIFE

call / apply

fun.call(thisArg[, arg1[, arg2[, ...]]])
fun.apply(thisArg[, argsArray])

event loop / async

à trier

Tests unitaires

Voir mocha, chai

Débug

http://berzniz.com/post/78260747646/5-javascript-debugging-tips-youll-start-using-today

logging / console

console.log("hello world");
var bar = {name: 'kitten', status: 'playful'}
console.log(2,4,6,8,"foo",bar);
console.log("%s is %d years old.", "Bob", 42);
console.group("console levels tests");
 console.log(  "console.log");
 console.debug("console.debug");
 console.info( "console.info");
 console.warn( "console.warn");
 console.error("console.error");
console.groupEnd();
console.trace();
console.dir(bar);
console.assert(false);

débogueur chrome

http://www.html5rocks.com/en/tutorials/developertools/async-call-stack/

DOM

DOM Manipulation

var para = document.getElementsByTagName('p')[0];
para.style.display = 'none';

getElementsByName

nodeName, nodeValue, nodeType, innerHTML, outerHTML

document.getElementById('mini-loader-errors').appendChild(document.createTextNode('Error loading the page !'));

document.getElementById('expected-rsrc-count').innerHTML = this.expected_rsrc_count;

document.getElementById('connected-rsrc-pane').style.display = 'none'; // 'block';

Voir page dédiée : XPath

Events

Dynamic styling

Asynchronicité

debounce / throttling

async

https://github.com/caolan/async

fs.stat(param, callback(err, result))
async.map(['file1','file2','file3'], fs.stat, function(err, results){
   // results is now an array of stats for each file
});
fs.exists(param, callback(err, result))
async.filter(['file1','file2','file3'], fs.exists, function(results){
   // results now equals an array of the existing files
});
async.parallel([
   function(){ ... },
   function(){ ... }
], callback);
async.series([
   function(){ ... },
   function(){ ... }
]);
async.waterfall([
   function(callback){
       callback(null, 'one', 'two');
   },
   function(arg1, arg2, callback){
     // arg1 now equals 'one' and arg2 now equals 'two'
       callback(null, 'three');
   },
   function(arg1, callback){
       // arg1 now equals 'three'
       callback(null, 'done');
   }
], function (err, result) {
  // result now equals 'done'
});

promises

Doc

Avancé

standard

Promise.resolve(value)
Promise.reject(new Error('Whatever'));

Reactive

voir flux#Reactive extensions

Avancé

foreign interface

C++

accesseurs

http://www.2ality.com/2015/08/object-literals-es5.html

   var obj = {
       get foo() {
           return Math.random();
       },
       set foo(value) {
           console.log('SET foo = '+value);
       },
   };

Let’s use obj in a REPL:

   > obj.foo
   0.6029663002118468
   > obj.foo
   0.99780507478863
   > obj.foo = 123;
   SET foo = 123

Ajax

Mieux vaut utiliser https://github.com/visionmedia/superagent et tests avec supertest

JSONP

  var jqxhr = $.ajax({
      url: "http://tu1.utp.boursedeparis.fr:8081",
      /*beforeSend: function ( xhr ) {
            xhr.overrideMimeType("text/plain; charset=x-user-defined");
         },*/
         function( data, textStatus, jqXHR ) {
            Q.error("[global_state_machine] success..." + textStatus);
            ccf_client.attempt_event('_connection_success');
         }*/
         dataType: "jsonp",
      })
      //.always(function() { alert("complete"); })
      //.done(function() { alert("success"); })
      .fail(function( jqXHR, textStatus, errorThrown ) {
         Q.error("[global_state_machine] error... " + textStatus + errorThrown);
         ccf_client.attempt_event('_connection_failed');
      });

cache

??

web workers

"Worker threads run their code (and all imported scripts) synchronously from top to bottom, and then enter an asynchronous phase in which they respond to events and timers. If a worker registers an onmessage event handler, it will never exit as long as there is a possibility that message events will still arrive. But if a worker doesn’t listen for messages, it will run until there are no further pending tasks (such as download and timers) and all task-related callbacks have been called."

Page side :

var worker = new Worker("utils/loader.js");
worker.onmessage = function(e) {
  var message = e.data;                    // Get message from event
  console.log("URL contents: " + message); // Do something with it
}
worker.onerror = function(e) {
  // Log the error message, including worker filename and line number
  console.log("Error at " + e.filename + ":" + e.lineno + ": " +
               e.message);
}

Worker side

// NOTE : Relative URLs are resolved relative to the URL that was passed to the Worker() constructor.
// importScripts() does not try to keep track of what scripts have already loaded and does nothing to prevent dependency cycles.
// importScripts() is a synchronous function: it does not return until all of the scripts have loaded and executed
importScripts("collections/Set.js", "collections/Map.js", "utils/base64.js");
postMessage()
onmessage
close()

Notes

  • Vu expérimentalement : console.log() avec plusieurs paramètres ne fonctionne pas !

Utiliser require.js : http://requirejs.org/docs/api.html#webworker

Libs (browser + node)

Unicode

ES6 / ES2015 / ECMA 6

features

général

support

http://kangax.github.io/compat-table/es6/

Node

Browsers *

refacto / conception / bonnes pratiques

optimisation

à traiter

http://robots.thoughtbot.com/replace-coffeescript-with-es6

asm.js

démo https://dev.windows.com/en-us/microsoft-edge/testdrive/demos/chess/

outils

https://medium.com/javascript-scene/must-see-javascript-dev-tools-that-put-other-dev-tools-to-shame-aca6d3e3d925

analyse statique

documentation

analyse dynamique et traque fuites mémoire

webkit-devtools-agent is king, node and browser. https://github.com/c4milo/node-webkit-agent

Node

divers

à trier

Category:Technologie web Category:Technologie web majeure

⚠️ **GitHub.com Fallback** ⚠️