background preloader

JS

Facebook Twitter

Performance

Улучшаем сжимаемость Javascript-кода. При сжатии javascript-кода минификатор делает две основные вещи. В статье рассматриваются минификаторы YUI Compressor и ShrinkSafe. На момент написания это лучшие минификаторы javascript. Есть несколько несложных приемов программирования, которые могут увеличить сжимаемость JS-кода. Минификатор заменяет все локальные переменные на более короткие (Также о сжатии в статье Сжатие Javascript и CSS). После минификации станет: Заведомо локальные переменные moon, spaceShip могут быть безопасно заменены на более короткие A,B. С другой стороны, название функции в этом скрипте - глобальная переменная, оно не сжимается, чтобы сохранить возможность обращения к функции.

По тем же причинам не сжимается вызов SpaceShip и методы fly, getDistance(). Итак, сделаем какой-нибудь более реальный скрипт и напустим на него YUI Compressor. К сожалению, в YUI Compressor нельзя отключить убивание переводов строки, поэтому получилось такое: ShrinkSafe замечательно сжимает все, что только может. Например, вот так: Jamespadolsey's gist: 527683. Detect IE6 in javascript - JavaScript. UsingConditionalCommentWithClosureCompiler - closure-compiler - Using Internet Explorer's "conditional compilation" with Closure Compiler - Closure Compiler. Docco.coffee. Docco is a quick-and-dirty documentation generator, written in Literate CoffeeScript. It produces an HTML document that displays your comments intermingled with your code.

All prose is passed through Markdown, and code is passed through Highlight.js syntax highlighting. This page is the result of running Docco against its own source file. Install Docco with npm: sudo npm install -g doccoRun it against your code: docco src/*.coffee There is no “Step 3”. The Docco source is available on GitHub, and is released under the MIT license. Docco can be used to process code written in any programming language. Partners in Crime: If Node.js doesn’t run on your platform, or you’d prefer a more convenient package, get Ryan Tomayko‘s Rocco, the Ruby port that’s available as a gem.If you’re writing shell scripts, try Shocco, a port for the POSIX shell, also by Mr.

Note that not all ports will support all Docco features … yet. Main Documentation Generation Functions Configuration Helpers & Initial Setup h. A Better is_a Function for JS. In 2007 I have posted about get_class and is_a functions in JavaScript in order to simulate original PHP functions. Well ... that was crap, since a much simpler and meaningful version of the is_a function can be easily summarized like this: ... or even smaller with explicit cast ... An "even smaller" alternative via @kentaromiura function is_a(who, what) { return who !

= null && Object(who) instanceof what; } Here a usage example: alert([ is_a(false, Boolean), is_a("", String), is_a(123, Number), is_a(/r/, RegExp), is_a([], Array), is_a(null, Object), is_a(undefined, Object) ]); As twitted few minutes ago, an alternative would be to pollute the Object.prototype: However, this way would not scale with null and undefined so that per each test we need to check them and this is boring.Finally, I would not worry about cross frame variables since via postMessage everything has to be serialized and unserialized.

Flexible Nav jQuery library. Flexible Nav is a small jQuery library which add a smart navigation bar on the right of the page. It improves a web page navigation and helps to visualize different sections of a document, an article,.. any web page. Nav links are distributed proportionally to the page sections. See how your scrollbar "weds" these links :) You can easily use it on any website with the Bookmarklet . Save this bookmark by drag and dropping it in your bar... FlexibleNav bookmarklet ...and click on it in any website ! This page is a 3-in-one document! First, it explains goals and possible usages of the library. Download You can also use it in your websites. Download or fork me on github Usages Generation and Flexibility The library can generate for you the nav sidebar content providing elements to display in navigation.

By default, it uses h1 to h3 elements to retrieve and locate the different sections of a document but you can override these elements selector. You have usually two kind of selected elements to use: 140byt.es. Sniffing Internet Explorer via JavaScript. I’ve been reviewing bug submissions for the SWFObject project and was reminded of a big problem with SWFObject 2.2: the JavaScript technique it uses for detecting Internet Explorer does not work in Internet Explorer 9. SWFObject 2.2 currently uses an IE detection technique proposed by Andrea Giammarchi in 2009: It’s a hack that relied on Internet Explorer’s unique handling of vertical spaces (\v).

Now that it has stopped working, I decided to take a quick look at what others are doing. It’s 4 years old, but still works like a charm. The only problem is that some JavaScript compressors and optimizers (including YUI Compressor and Google Closure) have a hard time with the inline comment and strip it out. One way to get around the compressor issue (as pointed out by a commenter on Dean Edwards’ post) is to wrap the conditional compilation statement in an eval() function: Since eval() is evil, I won’t use this approach. Is it perfect? What are the Frameworks using? Why sniff in the first place? 32 bytes, ehr ... 9, ehr ... 7!!! to know if your browser is IE. Fixing the JavaScript typeof operator. Working with JavaScript’s typeof operator is a bit like operating a clapped-out old car (or an early model Dell Inspiron). It gets the job done (mostly) and you learn to work around the quirks – but you probably aspire to something better. In this article I’ll give a brief overview of typeof before introducing a tiny new function which is a fully-loaded, more reliable alternative that works directly with the language internals.

The typeOf Operator How is it used? Since typeof is a unary operator, the operand follows the operator. No additional punctuation is required. But it works when I call it as a function? The typeof operator is not a function. What does it return? The returned value is a somewhat arbitrary representation of the operand’s type. What’s wrong with typeof? The most glaring issue is that typeof null returns “object”. Other than that, typeof is just not very discriminating. Oh and you’ll hear folks complaining about this… [[Class]] Object.prototype.toString [object [[Class]]] 1. Performance of Javascript (Binary) Byte Arrays in Modern Browsers « searching for signal.

A little over a year ago I started the noVNC project, an HTML5 VNC client. noVNC does a lot of processing of binary byte array data and so array performance is a large predictor of overall noVNC performance. I had high hopes that one of the new binary byte array data types accessible to Javascript (in modern browsers) would give noVNC a large performance boost. In this post I describe some of my results from testing these binary byte array types. After reading the title, you may have thought: "Wait ...

Javascript doesn't have binary byte arrays. " Jump list: The Options Typed Arrays: Those who follow browser development and HTML standardization may already be aware of one of these array types. The following Javascript creates an ArrayBuffer view that contains 1000 unsigned byte elements that are initialized to 0: var arr = Uint8Array(new ArrayBuffer(1000)); ImageData arrays: But there is an older and more widely supported form of binary byte arrays available to Javascript programs: ImageData. The JS, By Douglas Crockford (1 of 4) Douglas Crockford: Advanced Javascript (1 of 3) - Video - Sclipo.

Douglas Crockford Javascript Videos. Douglas Crockford Javascript Videos 13 flv videos | 246MB+258MB+151MB+167MB+212MB+70MB | Total duration 6hr 24min Yahoo! JavaScript Architect Douglas Crockford covers JavaScript in a series of tutorial and lecture videos. Class 1 - The JavaScript Programming Language Yahoo! JavaScript Architect Douglas Crockford provides a comprehensive introduction to the JavaScript Programming Language in this four-part video.

Part 1: 30:58 Part 2: 31:08 Part 3: 29:08 Part 4: 19:47 Class 2 - The Theory of the DOM Douglas Crockford teaches "An Inconvenient API: The Theory of the Dom. " Part 1: 31:11 Part 2: 21:25 Part 3: 26:24 Class 3 - Advanced Javascript Douglas Crockford teaches "Advanced JavaScript. "

Libs

A.Ruzanov - Fast base64 encoding in js. And test results. Programming languages - What should every JavaScript programmer know. DOM. Online javascript beautifier. Nzakas/computer-science-in-javascript - GitHub. LanguageFeatures - traceur-compiler - Traceur Language Features - Google's vehicle for Javascript Language Design Experimentation.

Property Method Assignment These features are proposals for ECMAScript Harmony unless otherwise noted. Classes This implements class syntax and semantics as described in the ES6 draft spec. In earlier versions of Traceur we had more feature rich classes but in the spirit of Harmony we have scaled back and are now only supporting the minimal class proposal. class Monster extends Character { constructor(x, y, name) { super(x, y); this.name = name; this.health_ = 100; } attack(character) { super.attack(character); } get isAlive() { return this.health > 0; } get health() { return this.health_; } set health(value) { if (value < 0) throw new Error('Health must be non-negative.'); this.health_ = value; }} Here's an example of subclassing an HTML button: class CustomButton extends HTMLButtonElement { constructor() { this.value = 'Custom Button'; } // ... other methods ...}var button = new CustomButton();document.body.appendChild(button); Warning This is currently not supported.

Modules Generators. Traceur-compiler - Google's vehicle for Javascript Language Design Experimentation. Ten Oddities And Secrets About JavaScript - Smashing Magazine. Using continue with a label. Summary Terminates execution of the statements in the current iteration of the current or labelled loop, and continues execution of the loop with the next iteration. Version Information Syntax continue [ label ]; Parameters label Identifier associated with the label of the statement. Description In contrast to the break statement, continue does not terminate the execution of the loop entirely: instead, In a while loop, it jumps back to the condition. The continue statement can include an optional label that allows the program to jump to the next iteration of a labelled loop statement instead of the current loop. Examples Example: Using continue with while The following example shows a while loop that has a continue statement that executes when the value of i is 3.

I = 0; n = 0;while (i < 5) { i++; if (i === 3) { continue; } n += i;} Example: Using continue with a label In the following example, a statement labeled checkiandj contains a statement labeled checkj. See also break, label. Label. The labeled statement can be used with break or continue statements. It is prefixing a statement with an identifier which you can refer to. Syntax label : statement label Any JavaScript identifier that is not a reserved word. statement Statements. break can be used with any labeled statement, and continue can be used with looping labeled statements. Description You can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution. Note that JavaScript has NO goto statement, you can only use labels with break or continue.

Examples Using a labeled continue with for loops Using a labeled continue statement Given an array of items and an array of tests, this example counts the number of items that passes all the tests. var itemsPassed = 0;var i, j; top:for (i = 0; i < items.length; i++){ for (j = 0; j < tests.length; j++) if (! Using a labeled break with for loops Using a labeled break statement Specifications. Exceprion Handling. It's sad but true - error-free code is still largely a Utopian dream. No matter how careful you are, no matter how deep your knowledge or how good your IDE, you're bound to slip up sooner or later.

And when you do, and your routines decide to go AWOL, you need to take remedial action. Most programming languages come with built-in exception handling capabilities. These exception handlers make it possible to catch errors and resolve them sensibly, thereby insulating the user from complex decisions and incomprehensible technical information. Up until recently, JavaScript was *not* one of the languages with sophisticated exception handling. That's where this article comes in. Normally, when a JavaScript program encounters an error, be it syntactical or logical, it exits the program at that stage itself with a message indicating the cause of the error. The term "exceptions" refers to those errors which can be tracked and controlled. An example might make this clearer. Oops! Vara count = 99. Error - MDN Docs.

The Error constructor creates an error object. Instances of Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. See below for standard built-in error types. Syntax new Error([[, [, ]]]) Parameters message Optional. FileName Optional. LineNumber Optional. Description Runtime errors result in new Error objects being created and thrown. This page documents the use of the Error object itself and its use as a constructor function.

Error types Besides the generic Error constructor, there are six other core error constructors in JavaScript. EvalError Creates an instance representing an error that occurs regarding the global function eval(). InternalError Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. RangeError Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range. ReferenceError SyntaxError URIError. How do I create a custom Error in JavaScript? What's a good way to extend Error in JavaScript? JavaScript self-made Error object comparison.

Argumentation in previous node is wrong. "finally" block. JavaScript also allows you to add a "finally" block to the "try-catch" block discussed previously. The "finally" block contains statements that are executed regardless of whether an exception is generated or not in the "try-catch" block. try { execute this block } catch (error) { execute this block if error } finally { execute this block after the try block } If an exception is encountered when running the code within the "try" block, JavaScript will stop execution at that point, and look for a "catch" block to handle it.

Once the error has been handled (or if no "catch" block exists), control passes to the "finally" block. Take a look at the next example to see how this works: Here's the output: The following error occurred: TypeError - 'a' is undefined Thank you for playing. It's important to note that the code in the "finally" block will be executed even if errors are encountered in the corresponding "try" block. Why use the "finally" Block. When an exception occurs, execution stops and control is given to the closest exception handler. This often means that lines of code you expect to always be called are not executed. Some resource cleanup, such as closing a file, must always be executed even if an exception is thrown. To accomplish this, you can use a finally block.

A finally block is always executed, regardless of whether an exception is thrown. Object-Oriented JavaScript. Subclassing The JavaScript Array Object. Sorry Dean, I subclassed Array again. How ECMAScript 5 still does not allow to subclass an array. Using Prototype Property in JavaScript. Object-Oriented JavaScript Book. Prototypal Inheritance. Simple “Class” Instantiation. Simple JavaScript Inheritance. Understanding John Resig's "Simple JavaScript Inheritance"

Prototypal Inheritance Explained. How does JavaScript .prototype work? Different Patterns. Learning Advanced JavaScript. Public, Privileged, Private. Creating static methods, instance methods. Static variables. You must remember 'this' HasOwnProperties. Object.create() vs. constructor vs. object literal.