Ссылки о веб-разработке за ноябрь 2009

Сергей Мартынов: Краткий пересказ Effective Go на русском языке

Сергей Мартынов
Краткий пересказ Effective Go на русском языке - http://eao197.narod.ru/desc...

Minutes and Resolutions November F2F TPAC Santa Clara

Shared by arty
CSS3 Multicol — Candidate Recommendation

Drop Shadows and Filter Effects

Full minutes

Media Queries for HTML5 Video

It is proposed to add media queries to <video> and then to also define queries for the user's special needs. These new media queries will go into a new media queries module.

Full minutes

CSS2.1 Test Suite Status

Reviewed status of CSS2.1 test suite. Still on track wrt roadmap. fantasai has a rough coverage report, but is missing many of Microsoft's tests because they don't have the right metadata. (Microsoft's management is preventing Arron from correcting the tests.)

Full minutes


Full minutes

CSS3 Color

Full minutes

display: run-in

Worked through issues summarized in Bert's email

Full minutes

Size to Fit for text

Reviewed examples of copyfitting by changing the font size and various past proposals for addressing some of the use cases. Intentions can be split into:

dbaron proposes a copyfit property to trigger these behaviors. An alternate proposal is to incorporate this into text-justify.

Related behaviors were mentioned: specifically, triggering justification on the last line only if it's longer than a certain threshold; and specifying a minimum length for the last line, which would trigger whole-paragraph justification if the last line were not long enough.

Conclusion is to add some notes to css3-text and leave it for the next active editor to deal with.

Full minutes

CSS3 Multicol

Full minutes

Grid, Flexbox, and Template Layout Interactions

Full minutes

font-variant and font feature support in CSS

John Daggett proposes adding subproperties to font-variant for allowing access to the more common OpenType features. font-variant would become a shorthand for font-variant-ligatures, font-variant-alternates, font-variant-caps, font-variant-numeric, font-variant-position.

There some concern about fallback behavior for subscript and superscript features, and winding up with either a complete loss of semantics or a double-sub/superscript rendering.

John notes that OpenType has language-sensitive rendering, and proposes allowing an explicit choice of typographic language different from the content language.

There's concern about exposing alternate glyphs from a generic mechanism such as font-variant, because the choices are very font-specific. Proposals include dealing with it in @font-face; and pairing the glyph set number with the font name so that it only triggers on that font name.

Otherwise the WG is mostly in agreement and pressures jdaggett into putting his proposal in the editor's draft. :)

Full minutes

text-overflow: ellipsis

Resolved: Only horizontal overflow triggers for text-overflow: ellipsis. Add a new keyword for handling ellipsis due to vertical overflow (where the ellipsis appears on the last line only).

Discussed other issues with text-overflow, including:

Apparently some of these questions were resolved over lunch.

Full minutes

Transitions, Transforms, and Animations

Full minutes


Full minutes Addendum

Brad Fitzpatrick: Google Profiles are now OpenIDs. Also, gmail webfinger declares that now too. #openid #webfinger

Brad Fitzpatrick
Google Profiles are now OpenIDs. Also, gmail webfinger declares that now too. #openid #webfinger
Lora Lufark, β-Кот Шредингера, arty and 4 other people liked this

A. Khmelevsky™: Identity in the Browser (Firefox)

A. Khmelevsky™
Identity in the Browser (Firefox) - http://www.azarask.in/blog...
Identity in the Browser (Firefox) Identity in the Browser (Firefox) Identity in the Browser (Firefox)
Alexey Ivanov, arty, Krassus and 3 other people liked this
"The browser is your personal and trusted agent to the web. It’s the only actor on the Internet stage which both knows everything you do on the web, and never has to let that data leave the privacy of your desktop. Your browser knows you (or, at least, should). At Mozilla Labs, we’ve been working on some potential integrations of identity directly into the browser. Note, this is an extremely rough draft." - A. Khmelevsky™
Interesting Sign In solution built-in browser by Aza Raskin. - A. Khmelevsky™

Apple is not evil. iPhone developers are stupid.

Shared by arty
Jobs showed His chosen people the straight and narrow path to enlightenment, but they ignored His word. Therefore He unleashed the scourge of the App Store upon them. Good for Him. He should do stuff like that more often.

In his “Apple’s mistake” essay Paul Graham makes an unwarranted assumption; an assumption everybody who’s currently involved in the Great App Store Debate seems to be making.

The fundamental problem on the iPhone is not Apple’s App Store approval policies, but the iPhone developers’ arrogant disdain for Web technologies.

It was only last Friday I told a roomful of Web developers that Apple is evil, and a spontaneous applause erupted. Since then, however, I have changed my mind completely. The Web developers and I were wrong.

Apple is not evil. iPhone developers are stupid. Their problems with the App Store approval process are entirely their own fault and they deserve no commiseration.

I hope the App Store approval process sticks around for a loooooooong time.

Update: I was wrong about Web apps being able to replace native apps right now. I was wrong about the iPhone developers’ mindset. They aren’t stupid. Read my follow-up post.

Thou Shalt Not Spec a Feature that Might Inadvertently Compete with RDF when Used Contrary to How It Is Designed to Be Used

From the minutes of the TAG meeting on November 2nd 2009.


jQSlickWrap. Clever jQuery plugin which allows text to wrap around irregularly shaped images, by processing the image with canvas and rewriting it as a sequence of floated horizontal bars of different widths. It’s a a modern variant of the the ragged float trick first introduced by Eric Meyer.

Major IE8 flaw makes 'safe' sites unsafe

Major IE8 flaw makes ’safe’ sites unsafe. IE8 has an XSS protection feature which rewrites potentially harmful code in HTML pages—I think it looks for suspicious input in query strings which appears to have been output directly on the page. Unfortunately it turns out there’s a flaw in the feature that can allow attackers to rewrite safe pages to introduce XSS flaws. Google are serving all of their pages with the X-XSS-Protection: 0 header. Until the fix is released, that’s probably a good idea.

Программирование под *nix / Hello World! как ему следует быть на C в Linux

Очень многие начинающие программисты думают, что знают, как написать Hello World. Естественно, с этого примера ведь и начинается большинство учебников.
А давайте посмотрим, как это делается.
Обычно в учебнике по C эта программа выглядит примерно так:
#include <stdio.h>
void main()
    printf("Hello world\n");

Читать дальше

The Top 10 Most Common API Pitfalls

The Top 10 Most Common API Pitfalls

Alexander Zhuravlev: nginx_http_push_module - Comet For The People

Alexander Zhuravlev
nginx_http_push_module - Comet For The People - http://pushmodule.slact.net/

Django Framework / Популярные django-приложения

В данной статье я расскажу о популярных django-приложениях. Незнание их является дурным тоном и вообще преступлением против magic pony.

Читать дальше →

Deep Tracing of Internet Explorer

After reading a recent post by Steve Souders concerning a free tool called dynaTrace Ajax, I was intrigued. It claimed to provide full tracing analysis of Internet Explorer 6-8 (including JavaScript, rendering, and network traffic). Giving it a try I was very impressed. I tested against a few web sites but got the most interesting results running against the JavaScript-heavy Gmail in Internet Explorer 8.

I typically don't write about most performance analysis tools because, frankly, most of them are quite bland and don't provide very interesting information or analysis. dynaTrace provides some information that I've never seen before - in any tool on any browser.

dynaTrace Ajax works by sticking low-level instrumentation into Internet Explorer when it launches, capturing any activity that occurs - and I mean virtually any activity that you can imagine. I noticed very little slow down when running the browser in tracing mode (although it's sometimes hard to tell, considering the browser). However all of the tracing is recorded and saved for later, making it easy to record sessions for later analysis.

dynaTrace Ajax

Above is the result of a recorded session, logging in to Gmail, reading a mail, and logging back out again. All aspects of the session are saved: Network requests, JavaScript source, all DOM events, etc. I had a hard time finding information that wasn't saved by the tool.

This is the full timeline view of loading a single the Gmail inbox. All network traffic, JavaScript parsing and execution, browser events, and CPU load can be seen.

You can select a segment of the timeline and get a view that looks like the following:

In the above you can see a clearer picture of the exact interactions happening. A phenomenal amount of inline JavaScript execution followed by page layout calculation coinciding with loading of some data over the network. You can mouse over the individual blocks on the timeline to get more information (such as if the JavaScript execute was the result of a timer or what Ajax requests were firing to cause the network traffic). Additionally you can click the blocks to dive in and take a deeper view of the trace.

Digging in to the execution of an XMLHttpRequest on a page we get to see some of the full execution stack trace - and this is where the tools starts to become really interesting. The tool is capable of tracing across JavaScript, through the native XMLHttpRequest, through the network request, and back to the handler that fires when the request is done. This is phenomenal. This is the first tool that I've seen that's capable of tracing through native methods to give you a picture of what activity triggers which actions and the complete ramifications of what happens (in both CPU usage and execution time).

Note that in the stack trace view you can click any piece of code and see its location anywhere inside the source code (and this even works after you've already closed the browser and have moved on - all source code is saved for later analysis).

While it's interesting to trace through code to look for problems the bigger question is usually: Where are slowdowns occurring? This is where the HotPath view comes into play:

This looks like a typical execution count view - like the one that you might see in Internet Explorer's built in tool or in Firebug - except for one important point: This view includes JavaScript parsing and layout rendering times. This is huge! No other tool provides information on how long it takes to parse all the JavaScript code on your site or how long it takes to do all the rendering. Clicking those entries allows you to see a breakdown of every time JavaScript was parsed or a layout was rendered - from which you can trace back to get even more information about what caused those actions. I don't want to seem too excited but I really am, this is just an incredible amount of information - and it gets even better:

Not only can you see the execution count for your defined JavaScript methods but you can also see execution time for the built-in DOM methods! Wondering what native method calls are slowing down your application? Wonder no more. From the HotSpot view you can filter by DOM or regular JavaScript and see exactly where execution time is going and what methods are so slow.

dynaTrace provides an additional view, called PurePath that attempts to figure out problematic scripts:

Just another way to try and get a full picture as to where your application is slowing down and what may be causing the problem.

In all I'm hugely impressed with this (free!) tool and am already using it to do more testing and performance analysis on my code. I don't think any browser has ever had a tool capable of this type of analysis, let alone Internet Explorer 6 and 7, which are still a very real part of any developer's workflow.

I chatted with some of the dynaTrace guys and asked them to add in memory profiling and to support more browsers. If they can provide this quality of instrumentation for CPU and execution time I hope they can do the same for memory usage, the next un-tapped realm of JavaScript performance analysis.

10 Uses for Blocks in C/Objective-C

10 Uses for Blocks in C/Objective-C. Part of the Cocoa for Scientists series, which is by far the best free Objective-C / Cocoa tutorial I’ve seen anywhere.

Mike Shakin: Важно! Google будет учитывать скорость сайтов (Matt Cutts) (англ): http://tinyurl.com/yzxx7yh #google

Mike Shakin
Важно! Google будет учитывать скорость сайтов (Matt Cutts) (англ): http://videos.webpronews.com/2009... #google

JavaScript / Getters & Setters в IE5+

Вот этим навеяло habrahabr.ru/blogs/javascript/66242/

Вопреки расхожему мнению ИЕ все таки умеет назначать аксессоры, правда только в VB, чего для некоторых задач вполне достаточно.

<script language="vbscript">
' Объявляем класс, экземпляр которого в последствии будем использовать из яваскрипта
Class Accessor
  Public Property Let hook(val)  ' объявляем сеттер для свойства hook класса Accessor
   MsgBox val
  End Property
End Class

Dim access ' объявление переменных в VB обязательно
Set access = New Accessor  ' создаем экземпляр класса Accessor

<script language="jscript">
// т.к. у VB и JS общее пространство имен, можно вполне использовать созданный ранее access
access.hook = 'ololo';

* This source code was highlighted with Source Code Highlighter.

Другими словами аксессоры есть в VB, VB есть во всех IE и пространство имен VB и JS общее, можно пользовать.
Кроссбраузерный пример

Информационная безопасность / Фундаментальный баг Adobe Flash не будут исправлять

Специалисты по безопасности из Foreground Security обнаружили проблему с Adobe Flash, которая затрагивает почти все сайты, поддерживающие загрузку пользовательского контента, даже если сам сайт формально не показывает Flash. Дело в том, что ничто не мешает сделать object/embed на какой-нибудь страничке, не имеющей отношения к сайту, потому как Flash имеет доступ к куки того домена, с которого он загружен (а не того, где расположен тег object).

Проблема заключается в свойстве Actionscript same-origin, которое допускает выполнение активного контента в рамках данного домена. Но если UGC можно загрузить на доверенный сайт, то вредоносный скрипт будет выполнится у всех посетителей этого сайта, у которых установлен Flash.

Компания Adobe сказала, что исправить баг очень непросто и переложила всю ответственность за защиту от вредоносного кода на администраторов сайтов. Рекомендуется выделять для хранения UGC отдельный домен. Но не всегда это возможно: даже сайт самой компании Adobe подвержен данной уязвимости.

Атаку можно проводить в том числе через Gmail (см. видео).

Высокая производительность / Протокол SPDY ускорит Сеть вдвое

Разработчики из компании Google только что объявили, что работают над новым сетевым протоколом SPDY (читается как SPeeDY, то есть «быстрый»), который должен проапгрейдить протокол HTTP и значительно повысить скорость работы всех типов соединений.

SPDY позволяет вдвое уменьшить задержку (latency) при работе через HTTP. Делается это за счёт трёх методов:

1) мультиплексирование запросов;
2) расстановка приоритетов для запросов;
3) сжатие заголовков HTTP.

Чтобы продемонстрировать все возможности SPDY, инженеры Google подняли тестовый веб-сервер и выпустили специальную версию браузера Chrome.

По итогам предварительного тестирования на канале максимальной толщины, выигрыш в скорости загрузки для 25 крупнейших сайтов интернета составлял до 55%.

Alex Kapranoff: Unifying the Conversations (Salmon Protocol)

Alex Kapranoff
Unifying the Conversations (Salmon Protocol) - http://www.salmon-protocol.org/
arty liked this
We want to stop fragmenting conversations on the Internet. The Salmon protocol defines how comments can swim upstream to the resource being discussed. It's open, standards based, decentralized, abuse resistant, and user centric. Interested? See http://salmon-protocol.org/ for more details, and join the mailing list to start participating. - Alex Kapranoff
забавно, что у них в неймспейсе домен без дефиса - arty

Go! vs Go

Francis McCabe writes:

I have been working on a programming language, also called Go, for the last 10 years. There have been papers published on this and I have a book.

I would appreciate it if google changed the name of this language; as I do not want to have to change my language!

More specifically, Francis’ language is called “Go!” (with an exclamation mark), and his book is self-published at Lulu. I get the feeling no one should be able to “reserve” a normal word for their product/ invention/ programming language and then block others from using it in the future – what are your thoughts?

[By Philipp Lenssen | Origin: Go! vs Go | Comments]

[Advertisement] Google books on Amazon

как добавить pubsubhubbub в блог на django

наверное, вначале стоит пояснить, что такое PubSubHubbub. Эта технология была придумана недавно как замена веб-пингам, позволяющим оповестить всех заинтересованных, что у вас в блоге появилась новая запись. Для этого при добавлении записи нужно было отправить http-запрос на один или несколько специализированных серверов, которые дальше сами рассылали уведомления всем подписавшимся. PubSubHubbub развивает эту идею дальше, добавляя в этот запрос само содержимое поста, так что заинтересованные сайты не ломятся все сразу в ваш блог, чтобы скачать фид и вынуть из него новый текст. Однако для большего нашего удобства работает и старый механизм: достаточно «пингануть» подходящий сервер, и он сам скачает фид, извлечёт из него пост, и разошлёт его подписчикам

кратко процесс можно описать так:

  1. вы добавляете запись
  2. ваш блог отправляет серверу сообщение «в таком-то фиде новое содержимое»
  3. сервер скачивает фид и находит в нём новый пост
  4. сервер отправляет всем подписанным на обновления этого фида новый пост

итак, что нужно сделать для подключения вашего блога на django к этой радости? Во-первых, выбрать PubSubHubbub-сервер. Я сам пока знаю только один: http://pubsubhubbub.appspot.com/. Пропишем его в настройках (settings.py):

PUSH_URL = u'http://pubsubhubbub.appspot.com/'

затем нужно скачать и установить питоновский модуль для публикации в PuSH. Установка после распаковки делается обычным sudo python setup.py install

после этого нужно в методе сохранения записи (тут я не могу давать конкретику, потому что не знаю внутренностей вашего блога) добавить собственно отправку оповещения:

from pubsubhubbub_publish import publish
publish(settings.PUSH_URL, u'http://your.blog/feed.url')

но это самый простой вариант, мне хочется оповещать ещё и об обновлениях в фидах тегов:

from pubsubhubbub_publish import publish
from django.core.urlresolvers import reverse as reverse
params = [settings.PUSH_URL, u'http://your.blog/feed.url']
params.extend(map(lambda tag: 'http://your.blog%s' % (reverse('tag_feed', args=[tag])), tags))

теперь остался последний шаг: нужно добавить в сам фид информацию о том, за ним можно следить при помощи PuSH. Вообще-то это должно делаться очень просто — добавлением в него вот такой строчки:

<link href="http://pubsubhubbub.appspot.com/" rel="hub" />

но в django для фидов используется навороченный Syndication Framework, поэтому придётся унаследоваться от стандартного класса отрисовки фида Atom1Feed и добавить строчку вот таким образом:

class PubSubHubbubEnabledFeed(Atom1Feed):
    def add_root_elements(self, handler):
        super(PubSubHubbubEnabledFeed, self).add_root_elements(handler)
        handler.addQuickElement(u'link', attrs={u'rel': u'hub', u'href': settings.PUSH_URL})

после этого в определениях классов фидов нужно заменить feed_type = Atom1Feed на feed_type = PubSubHubbubEnabledFeed

всё, добавление PuSH завершено! Пройдёт некоторое время, пока заинтересованные сайты узнают, что ваши фиды транслируют обновления таким способом, и после этого новые записи будут появляться на них практически моментально

ну а если вам хочется свести код минимуму, то наверное link можно прописать в фиде вручную, и вместо вызова метода publish просто отправлять на сервер запрос с параметрами hub.mode=publish&hub.url=yourfeedurls

кстати, вот обсуждение, которое сподвигло меня на доработку блога и этот пост

Alex Kapranoff: Бретт Слаткин заявил, что ЖЖ прямо сейчас запустил PubSubHubbub для всех блогов.

Alex Kapranoff
Бретт Слаткин заявил, что ЖЖ прямо сейчас запустил PubSubHubbub для всех блогов.
Алексей Мельчаков, buger, arty and 4 other people liked this
тут жж и упало :) - øv
В фидах появилась строчка <link rel="hub" href="http://pubsubhubbub.appspot.com/...> - Alex Kapranoff

Git / Особенности настройки git под windows

Проблемы с русскими символами в git

Когда вы начнете работать с версией git под windows в командной строке, вы столкнётесь со следующей проблемой — все сообщения git, в которых фигурируют русские символы будут нечитаемы. Имена файлов, на русском языке, будут выглядеть так — "\362\345\361\362", а тексты коммитов примерно так — <C8><ED><E8><F6><E8><E0><EB><E8><E7><E0><F6><E8><FF> <EF><F0><EE><E5><EA><F2><E0>. Т.е. исходная строка преобразуется в utf8 в соответствии с кодировкой latin1.


Sergey Homenkow: shopzilla: снижение времени ожидания страницы на 5 сек. увеличило доходы на 12% и снизило стоимость hardware на 50%. #gdd09ru

Sergey Homenkow
shopzilla: снижение времени ожидания страницы на 5 сек. увеличило доходы на 12% и снизило стоимость hardware на 50%. #gdd09ru
Velocity 09: Philip Dixon, "Shopzilla's Site Redo - You Get What You Measure" http://blip.tv/file/2290648 - Sergey Homenkow
Угу, переписали с Перла на Яву :) - Alex Kapranoff

Correct way to handle mobile browsers

Correct way to handle mobile browsers. If your site has an equivalent “mobile” version running on a different subdomain, how and when should you redirect mobile users to it and how should you let them opt in or opt out?

Цитата #405009

xxx: работаю в дурдоме
yyy: расказывай
xxx: мы с серёгой сидим в отдельном кабинете, кодим потихоньку, никого не трогаем. а в соседнем, сидят новенькие, человек пять. от нас к ним дверь напрямую и никогда не закрыта, они к нам постоянно бегают советоваться.
xxx: щас среди тишины из кабинета новеньких дикий крик "Великим докам по Java API, тройное ура!!!" и тут же хором "Ура! Ура! Ура!" и снова тишина


node.js. “Evented I/O for V8 JavaScript”—a JavaScript environment built on top of the super-fast V8 engine which provides event-based IO functionality for building highly concurrent TCP and HTTP servers. The API design is superb—everything is achieved using JavaScript events and callbacks (even regular file IO) and the small standard library ships with comprehensive support for HTTP and DNS. Overall it’s very similar to Twisted and friends, but JavaScript’s anonymous function syntax feels more natural than the Python equivalent. It compiles cleanly on Snow Leopard. Definitely a project to watch.

Sputniktests web runner


Sputniktests is an ECMA-262 conformance test suite made by Google. For those who don’t know, ECMA-262 is a standard behind well-known implementations like JScript, JavaScript and others. It’s what describes ECMAScript language.

Ever since Sputniktests release few months ago, I wanted to see how various browsers conform to the standard. Unfortunately it wasn’t very easy to do so. The way test suite could be executed is by running a python script, passing it an executable file of implementation such as V8 or Rhino. It wasn’t possible to just check conformance of any browser, especially browser with implementation that can’t be run separately.

I realized that a “web runner” for Sputniktests would be a useful thing to have and made one. In the end, it was a fun little exercise that made me understand ECMAScript language just a bit better.

Sputniktests screenshot

Web runner is merely a wrapper around original test suite, made fit to run in a browser environment. Its job is to execute tests sequentially and log any errors/failures in the process. When done, it reports elapsed time and number of errors.

Why it doesn’t always matter

Contrary to something like Acid test, Sputniktests is not immediately useful. Passing it fully does not necessarily make a browser more capable than the other one, with lower score. Many failures in modern browsers are rather insignificant from practical point of view and might not even affect any real world applications.

But there’s still a huge value in a conformance test suite like this. By testing every single detail of ECMAScript implementation, Sputniktests could help minimize regressions, both — functional and performance ones. It could serve as an excellent foundation for creating a new ECMAScript implementation. And last, but not least, it could help browser implementors find actual valid bugs in browser engines.

There’s an important point to understand regarding test suite failures: not all of them can — or even should — be fixed, and here’s why:

Proprietary extensions

It is a well-known fact that specifications allows implementations to introduce proprietary extensions. JScript and JavaScript ™ have been doing this for years. JScript’s conditional comments and JavaScript’s getters/setters demonstrate it very well. Another famous example is the way function declarations are treated in statements.

The point here is simple. Failure in Sputniktests can be the result of proprietary extension and might not even be considered a bug.

ECMAScript 5th edition

Another cause of “valid failures” might be the next edition of ECMAScript, currently draft. Some browsers have already started implementing parts of it and might fail to comply with 3rd edition that Sputniktests checks against. For-in handling is a good example of such “misunderstanding”.

Backwards compatibility

Finally, there’s always a beloved backwards compatibility to keep in mind. It might not be possible to fix otherwise valid bug/deviation due to this wonderful constraint.

How runner works

Runner works very simply. First, a query of tests is initialized and populated with all of the 5000+ tests. Then, a table of tests to ignore is initialized and is later used for… ignoring certain conflicting or complex tests. Finally, runner starts picking tests from the query, with a certain interval in between — to keep UI functional during this rather intensive process. Note that interval can be changed on the main screen before starting test suite but defaults to 50ms.

For every test, runner creates a new iframe, inserts it into a current document and writes a script element into it. This is done to keep tests isolated from each other, so that one test wouldn’t affect environment of the next one. Once script is executed, a meta data is printed to the screen: name of current test, total number of errors/failures, elapsed time, etc. Iframe is then deleted.

Before adding actual test script to an iframe, runner first injects a complementary script into it. That script defines global $ERROR, $FAIL and $PRINT and simply proxies them to same-named functions of main (parent) document. When these methods are called, they write an output to main document log area.

Browser comparison

So how do modern and not so modern browsers stand against standard? Here’s a comparison table (note that less score is better and that score represents total number of errors and failures):

Sputniktests results chart

We can see few interesting things here:

Notable deviations

Here are some of the bugs and quirks I noticed in few browsers. Each is accompanied with a short explanation.

1) for (var prop in null) { }
for (var prop in undefined) { }

These statements should actually result in a TypeError, and the explanation to that is pretty simple. During evaluation, an expression on the right hand side of in is being applied internal ToObject method. This internal method is the one that throws TypeError when given null or undefined value.

You might be wondering if ToObject is used anywhere else and has similar consequences? It does. Roughly, in 3 cases:

When foo evaluates to null or undefined, in any of these cases, TypeError is inevitable. Most browsers, however, throw error with first two statements, but not the last one. This is, arguably, a more useful behavior, even though technically, not ECMA-compliant.

Note that 5th edition of ECMAScript actually changes “for-in” to do exactly what most of the browsers currently do — not throw TypeError, but instead proceed as if foo was an empty object.

2) Number('\u00A0') === 0

When Number is called as a function, it performs type conversion. String to number type conversion is expressed in rather involved algorithm, but one of the simplest rules there is that when string consists of a whitespace character (or is empty), the result is 0. This means that both — Number('') and Number(' ') should evaluate to 0.

Some browsers, however, fail to comply in regards to the notion of whitespace character. Passing plain U+0020 does the job, but U+00A0 (and a whole slew of other ones) often doesn’t. Instead, NaN is returned for what should really be a 0.

3) parseFloat(“\u205F -1.1”)

Similar bug exists with handling of white space characters by parseFloat. Spec explains that any leading whitespace is ignored in input string. Something like parseFloat(' 2.5 ') should result in 2.5. And again, some implementations fail with rarer whitespace characters, such as U+205F or U+1680. Interestingly, only Opera is fully conforming here. Firefox and Webkit both fail one way or another.

4) Error.prototype.message

This one looks like a real bug in WebKit. WebKit throws “Unknown error” when merely attempting to access Error.prototype.message. Sputniktests actually managed to mess up here as well: test suite asserts that the property is an empty string, whereas specs say that Error.prototype.message is an implementation-dependent string (which means that it could as well be “foo-bar_BaZ”). Sputniktests need to check type of a property — typeof Error.prototype.message == 'string', and WebKit needs to stop throwing error.

5) EvalError and other xxxError ones are non-enumerable global properties

This one seems like a rather insignificant compliance. All properties of global object are specified to be non-enumerable (that is — have {DontEnum} internal attribute set on). However, at least WebKit enumerates over all of the global EvalError, RangeError, SyntaxError, etc.

6) [[Construct]] and .prototype of built-in objects.

There’s a whole slew of failures in Firefox due to built-in objects having what they shouldn’t have — prototype property and [[Construct]] method. To remind you, [[Construct]] is an internal method that’s called when applying new operator to an object — usually a function. It is basically what makes certain objects “constructable”, and what every native function object has intrinsically. The failing built-ins are global methods like parseInt, isNaN, encodeURI, as well as properties of Object.prototype, Array.prototype, and so on. To quote specs:

“None of the built-in functions described in this section shall initially have a prototype property unless otherwise specified in the description of a particular function”


“None of the built-in functions described in this section shall implement the internal [[Construct]] method unless otherwise specified in the description of a particular function.”

7) typeof new RegExp() === 'function'

This is probably one of the most famous WebKit deviations. As you might know, a large number of browsers make regex objects callable. Callable regular expressions allow to replace /(a|b)/.exec('a') with simply /(a|b)/('a'). I’m not sure where this non-standard behavior originates from, but it’s probably still kept around for backwards compatibility.

Interestingly, regex objects in WebKit seem to actually implement internal [[Call]] method. As per specs, any native object that implements [[Call]] should return “function” when applied typeof to, so WebKit merely follows the standard here. However, this little addition results in a side effect: regex objects are being reported as functions — typeof /x/ == 'function'.

Older Firefox (e.g. Firefox 2), by the way, behaves just like WebKit here.

8) new RegExp(undefined)

Another bug in Firefox is the way RegExp constructor treats pattern of undefined value. Specs mandate that when undefined, pattern should simply become an empty string (i.e. functionally identical to new RegExp('')). WebKit and Opera do just that, but Firefox converts undefined into its string representation — “undefined”, making regex behave as if it was created literally via /undefined/.

9) "".search() and "--undefined--".search()

This one is related to a previous bug. The purpose of String.prototype.search is to find offset within the string where a given pattern matches. As usual, all is nice and well, until we start dealing with non-trivial input values.

When given a non-regex object as a first argument, String.prototype.search should apply new RegExp() on it. This means that "".search() is functionally identical to "".search(new RegExp()), where undefined value is being applied new RegExp on. This expression essentially matches empty regex against empty string. The result of "".search(), quite obviously, should be 0, since empty regex (i.e. nothingness) matches at the very first position of empty string it’s being applied to.

Firefox, however, erroneously makes /undefined/ out of new RegExp(), and fails to match empty string at 0th position. For the very same reasons, it returns 2 in "--undefined--".search(), instead of correct 0.

10) "foo".substring(0, undefined);

Another weird quirk in Firefox is the way it handles second argument — ending position — of String.prototype.substring. Spec clearly states that when undefined, position is considered to be end of a string. For example, "foobar".substring(0, 2) should return "fo", but "foobar".substring(0)"foobar", since end position is considered to be at the end of a string.

Firefox does this partially right, producing proper result when argument is missing — "foobar".substring(0) === "foobar", but somehow fails to do the same, when passing undefined value explicitly — "foobar".substring(0, undefined) === "".

11) Line terminators in regex literals

An interesting quirk present in both — Firefox and Opera, but not in WebKit is related to regular expression literals. Spec makes it clear that regex literals are not allowed to have line terminators in their bodies. Not even when escaped with backslash. Firefox and Opera, however, seem to be perfectly fine with line terminators as long as those are escaped: eval("/\\\u000A/") results in an invalid regex literal that looks like:


Test suite errors and oversights

Sputniktests is a truly outstanding effort. I’m amazed at the amount of work that was put into it. However, the project is still in its infancy, and there are clearly some things that could be done better.

What striked me as being inconsistent and harmful is the way Sputniktests declares variables: sometimes using proper declarations (var foo = 'bar'), other times — using undeclared assignments (foo = bar). Undeclared assignments is a very bad practice, and there’s no reason to rely on it here or anywhere. It would be nice to see this changed in the future versions.

Other inconsistencies are with usage of $PRINT function. Sometimes it’s used to log additional information about tests, but not always.

There are cases when tests rely on compliance of other components and, as a result, give false positives. For example, a test for function expression in for-in statement assumes that prototype property of a function is enumerable:

for (x in function __func(){return 0;}){
  if (x == "prototype") 
    var __reached = 1;
if (__reached !== 1) {
    $ERROR('#2: function expession inside of for-in expression is allowed');

Per specification, prototype property of function object is in fact enumerable (it only has {DontDelete} attribute set on). But Firefox, for example, makes prototype non-enumerable and so fails this test. It fails it erroneously because function expression in for-in statements — what this test is actually supposed to ensure — is allowed in Firefox just fine.

A similar case of false results happens when testing for Array.prototype compliance. Array.prototype should itself be an array object; its internal [[Class]] should be that of all array objects — “Array”. The test, unfortunately, checks this compliance by deleting Array.prototype.toString, then calling toString on Array.prototype, letting Object.prototype.toString propagate through and ensuring that [[Class]] of Array.prototype is “Array”.

delete Array.prototype.toString;
if (Array.prototype.toString() !== "[object " + "Array" + "]") {
  $ERROR(/* ... */);

Clients that have non-deletable Array.prototype.toString fail this test even with fully conforming Array.prototype.

It might be safer to use call here, but then clients with non-conforming call could result in false positives as well:

// Is Array.prototype's [[Class]] an "Array"?
if (Object.prototype.toString.call(Array.prototype) !== "[object Array]") {
  $ERROR(/* ... */);

It is, of course, very hard to avoid these false positives. We can only guess which things are more likely to be compliant. We can also ignore these errors: if certain environment fails one test due to non-conformance of unrelated component, that component should simply be fixed as well.

Test suite has some minor inconsistencies — missing semicolons here and there, or extra ones (after statements). There are superfluous !(... == ...) used instead of (... != ...), as well as if (... == true) instead of if (...). I also noticed few missing conformance checks.

I have no doubt all these annoyances will be gone in the future.

Future work

Having extensive compliance test suite can really help modern browsers achieve even better conformance. I hope we’ll see some of the bugs revealed through the Sputniktests fixed in the near future. I hope we’ll also see less regressions, if browser implementors integrate it into existing test suites. I also hope Sputniktests can help people learn and understand ECMAScript better.

Web runner is published on github, so that anyone can contribute easily. There are many more things we can improve. I can think of additional features like running separate sections of tests or even individual ones; being able to see test contents right in a browser, or make it possible to pause/resume test suite execution.

Any comments, corrections, suggestions are as always very much welcomed.

And finally, I would like to, once again, thank Sputniktest team for their outstanding efforts to help move web forward.

boko: The Future State of Layout

The Future State of Layout - http://www.slideshare.net/stephen...
arty, Nop and Alex Kapranoff liked this
CSS3-Grid (MS), CSS3-Flexbox (Moz), CSS3-Layout (W3C) - boko

Шнява Мункер: Квайн квайнов: http://zw0rk.blogspot.com/2009/11/blog-post_08.html

Шнява Мункер
Квайн квайнов: http://zw0rk.blogspot.com/2009...
Donat, Sergey Dmitriev, Dmitry Oleynik and 18 other people liked this
Исходная программа на Руби генерит программу на Питоне, которая генерит программу на Перле, которая генерит программу на Lua, которая генерит программу на Окамле, которая генерит программу на Хаскелле, которая генерит программу на С, которая генерит программу на Джаве, которая генерит программу на Брейнфаке, которая генерит программу на Whitespace, которая генерит программу на Unlambda, которая генерит исходную программу снова на Руби. - Шнява Мункер
Brainfuck (переносы строк добавлены для читабельности) - falsefalse

JavaScript / [Ссылка] Тонкости ECMA-262-3. Часть 8. Стратегия передачи параметров в функцию

Evaluation strategy в ES.

Многие программисты уверены, что объекты в Javascript (как и в некоторых других привычных языках) передаются в функцию по ссылке, в то время как значения примитивных типов, передаются по значению. Более того, этот "факт" можно видеть в различных статьях, обсуждениях на форумах и даже книгах по Javascript. Однако, насколько точная это терминология и насколько верное это описание (и, что более важно, насколько верное это понимание), мы и разберём в этой статье.

Полезные rgba в IE

Вадим Макишвили описал несколько примеров применения rgba в Internet Explorer. Примеры очень и очень полезны, и я скопирую их (без картинок, за ними идите в исходный пост) к себе:

Сегодня, благодаря этому новому знанию, я понял как решить две труднорешаемые задачи. Издавна, чтобы сделать фон блока полупрозрачным, мы вынуждены были использовать или png-24 картинку в фоне или opacity-свойство.

Но в случае с png-24, для ИЕ6 нужно писать AlphaImageLoader фильтр, который катастрофически замедляет рендеринг страницы. А в случае с opacity приходилось придумывать трюки, чтобы дети блока не бледнели от родительского opacity.

А теперь проблему opacity можно забыть, как страшный сон:
background: #rgba
* html .block
filter:progid:DXImageTransform.Microsoft.gradient (startColorstr=#99000000, endColorstr=#99000000);

В начальной и конечной позиции один и тот же RGB (000000) и добавляю перед ним одно и то же значение Alpha (99) Значение Alpha указывается в 16-тиричной системе, где 00 – полностью прозрачный, а ff – непрозрачный пиксел

Я протестировал скорость рендеринга страницы, на которой выливается 300 элементов с gradient-фильтром — он не замедляет рендеринг и это сильно радует.

Но этот случай описывает ситуацию, когда нужно сделать однотонный полупрозрачный цвет, как например в модальных диалогах, когда вся остальная страница затемняется.

Иногда использовать png-24 всё-таки необходимо, как например в случае, когда нужно обрезать длинную неразрывную строку, уводя ее градиентом в непрозрачность.

В этом случае можно использовать второй способ.
background: url(image.png)
* html .block
filter:progid:DXImageTransform.Microsoft.gradient (startColorstr=#00ffffff, endColorstr=#ffffffff, GradientType=1);

GradientType принимает значение 1, если градиент рисуется слева-направо; и 0, если градиент сверху-вниз.

MSIE хороший браузер.

Компрессоры JavaScript и точка с запятой

Точка с запятой — один байт, перевод строки — один байт. Мне тут подумал, что лучше бы компрессоры JS выкидывали при сжатии не переводы строки, а точки с запятой (там где это возможно, конечно, например, пустой return в некоторых случаях нельзя завершить только переводом строки).

Тогда читаемость кода почти не снижалась бы (об обфускатарах я сейчас не говорю) и можно было бы легко понять где произошла ошибка, пропущенная в production (такое случается).

Douglas Crockford: “The State and Future of ECMAScript”

Shared by arty
Хорошее выступление о том, как развивается яваскрипт, куда пропала четвёртая версия, почему вредны эксперименты в стандартах, что нужно сделать с Бюро патентов, и прочая

Douglas Crockford of Yahoo! at YUICONF 2009, held at the Yahoo! HQ in Sunnyvale; October 28, 2009.

Yahoo!’s JavaScript architect Douglas Crockford gave the closing keynote at YUICONF 2009 last week. His talk, “The State and Future of ECMAScript,” was a detailed take on the events that Brendan Eich discussed the night before. Douglas addresses the current ECMAScript 5 proposals (coming up for vote at ECMA in December), details some of the remaining sticking points, and then goes on to distill some of the lessons learned in the course of the ECMA 4/3.1/5 process and what they tell us about the process of creating standards. As Brendan did the night before, Douglas looks ahead to the version of ECMAScript that will follow the current proposal.

Where Brendan compared the recent ECMA journey to Peter Jackson’s The Lord of the Rings (specifically, the fellowship of the ring), Douglas turns to Sidney Lumet’s 12 Angry Men for his metaphor. If you’re keeping track, Douglas is Gandalf in the first analogy and Peter Fonda in the second; Brendan is Frodo in the first and Juror #3 in the second.

If the video embed below doesn’t show up correctly in your RSS reader of choice, be sure to click through to watch the high-resolution version of the video on YUI Theater; the downloadable version is much smaller, optimized as it is for iPods, iPhones, and other handheld devices.

src="http://cosmos.bcst.yahoo.com/up/ypp/default/player.swf" type="application/x-shockwave-flash"

Other Recent YUI Theater Videos:

Subscribing to YUI Theater:

"Big ints allow you to write numbers that can’t be infinitely big, but can get really, really,..."

“Big ints allow you to write numbers that can’t be infinitely big, but can get really, really, really big. They’re used primarily in cryptography. It’s because they’re so useful in cryptography that I don’t want to put them in the language. One of the things we’ve learned is that if we allow people to roll their own crypto-routines, they invariably get them wrong.”

- Douglas Crockford — The State and Future of JavaScript

A quote from Alex Russell

It’s interesting to me how much [Closure] feels like a more advanced version of Dojo in many ways. There’s a familiar package system, the widgets are significantly more mature, and Julie and Ojan’s Editor component rocks. The APIs will feel familiar (if verbose) to Dojo users, the class hierarchies seem natural, and Closure even uses Acme, the Dojo CSS selector engine.

- Alex Russell

Google Closure, JavaScript Tools & Library

Google released a couple of internal tools of theirs into the open source world (must be make-people-happy week in Mountain View). One of them is the Closure Library for JavaScript; check the API reference for more. Another is called Closure Compiler, aiming to shrink and performance-optimize your JS and alert you to problems with it... there’s even an online app where you can paste your code into. The third in the bunch is called Closure Templates, and as Google explains in a overview blog post of theirs, you can think of it “as small components that you compose to form your user interface, instead of having to create one big template per page”.

[Thanks BizAbh, Steffi and Mbegin!]

[By Philipp Lenssen | Origin: Google Closure, JavaScript Tools & Library | Comments]

[Advertisement] Want to advertise here? Your ad will show in the blog and feed.

Javascript-библиотека от гугла (closure-library)

Javascript-библиотека от гугла (closure-library):

теперь с компилятором, декомпилятором для firefox, шаблонами и лунапарком

Проект Subversion переходит под крыло Apache Software Foundation

Компания Collabnet , поддерживающая разработку централизованной системы контроля версий Subversion , начала процесс передачи управления проектом организации Apache Software Foundation. В настоящий момент завершена первая стадия на пути перевода Subversion в разряд первичных проектов, развиваемых под эгидой Apache - код интегрирован в " инкубатор " для прохождения проверки.

JavaScript / placeholder.js

В HTML5 есть замечательный атрибут placeholder.

<input placeholder="inbox@disney.com">


Сейчас он работает только в webkit-браузерах (Safari, Google Chrome).

С помощью JS, не изобретая велосипедов, placeholder.js делает этот атрибут кроссбраузерным.

<input placeholder="inbox@disney.com" id="some_input">
<script type="text/javascript">
  inputPlaceholder( document.getElementById('some_input') )

placeholder.js (1.3 килобайта)

Alex Kapranoff: The Burning Edge » Blog Archive » 2009-11-03 Trunk builds

Alex Kapranoff
The Burning Edge » Blog Archive » 2009-11-03 Trunk builds - http://www.squarefree.com/burning...
arty liked this
"Fixed: 523771 - Support <input type=file multiple>." - Alex Kapranoff

Eril: К вопросу об обычных пользователях:

К вопросу об обычных пользователях:
Моя сестра (22 года) живет на Одноклассниках, мейлрушном Моем мире и в Яндекс-почте. Задачи типа "загрузить новые фотки на Мой мир", "отправить музыку по почте" или просто навигация по ссылкам сложностей не вызывают вообще. Но удивительным образом у нее никак не сформируется адекватная ментальная модель WIMP-интерфейса операционной системы в целом. Она в принципе не понимает идею оконного интерфейса. Если одно окно открывается поверх другого, для нее большой вопрос "как все вернуть обратно".Также она не понимает концепции вкладок в браузере, и если нужно открыть что-то новое, она закрывает текущее окно браузера, идет в меню "Пуск", заново запускает браузер и выбирает из закладок нужный сайт. - Eril
согласен с Eril, отдельных танцев с бубном стоило объяснение маме метафоры вкладок (про их восстановление, про отстутствие необходимости закрывать окно, про закладки и т.п.). Мама живет в Одноклассниках, Вконтакте, Скайпе, Гуглтоке, Пикасе, Гмэйле, GBookmarks, Гугльдоксах. Мама преподаватель, в прошлом тоже программист. - Гении о легендах :▒
Моя табы освоила сразу. Её больше озадачивают не табы, а интерфейсы сайтов. - Максим Россомахин

Web Inspector Updates

A number of exciting new features have been added to the Web Inspector since our last update. Today we would like to highlight some of those features! This post is also available in Japanese (日本語), thanks to Keishi Hattori (服部慶士).

If you would like to play with most of these features you will need to be running a recent WebKit Nightly. Once downloaded make sure that you enable the Web Inspector by checking “Show Develop menu in menu bar” under the Advanced tab in the Preferences.

Enabling the Inspector in Preferences

Editing Element Attributes and Style Properties #

Editing Element Attributes and Style Properties has been made even simpler and more developer friendly. The interfaces for editing attributes and properties now support tabbing to allow you to move between items, and create new items with ease.

Besides tabbing you can also add a new attributes to a node.  Start by hovering over the node in the Element’s Tree Hierarchy and after a polite wait a clickable template for a new attribute will appear.

Edit Element Attributes

Related Bug Reports: Add Element Attributes, Tabbing, and Improved UI.

Creating and Modifying CSS Rules and Selectors #

A powerful new feature in the Web Inspector allows you create new or modify existing CSS Rules and Selectors. We expect both developers and designers will find this very useful when experimenting with new ideas or tweaking existing designs.

The interface for working with selectors starts with a new Gear Menu in the Styles Sidebar Pane. Select “New Style Rule” and a new section will be created for you, pre-populated with an intelligent selector from the selection in the Elements Tree Hierarchy. Editing selectors is activated by double-clicking. Once again, tabbing will allow you to navigate between selectors and their properties.

When editing selectors there is visual feedback when you create or modify a selector that does not affect the selected node in the Elements Tree Hierarchy. This indicator helps detect errors when making changes.

Create and Modify CSS Selectors

One more tweak to the Styles Pane is that there is always a section for the selected node’s style attribute. This allows you to easily add style information to the node as you usually would via the Styles Pane instead of editing or creating a “style” attribute. This section is nearly always on top due to how CSS specificity works.

Related Bug Reports: Selectors Support and Move to Gear Menu.

CSS Color Representations #

Colors in the Styles Pane can be shown in any of their possible representations. For simple colors this includes short hex, full hex, rgb, hsl, and potentially a nickname. For advanced colors this includes rgba and hsla. For example the color “white” can be represented as: #FFF, #FFFFFF, rgb(255, 255, 255), hsl(0, 100%, 100%), and white.

You can use the Styles Pane’s Gear Menu to set your preferred representation. However, if you want to cycle through an individual color’s different representations you can do so by clicking on its associated color swatch.

Mutiple Color Representations

Related Bug Reports: Color Representations, Preference and Gear Menu, and UI Improvement.

DOM Storage #

The Storage Panel (formerly the Databases Panel) now allows you to monitor DOM Storage areas like localStorage and sessionStorage in a familiar datagrid. The DOM Storage datagrid displays live updates so monitoring changes is possible without manually refreshing the view.

Also, the familiar creation and editing techniques apply to the datagrid. To add a new key/value pair just double-click in any open area, or double-click an existing item to start editing. Tabbing works as you would expect.

Observing DOM Storage Key/Value Pairs

Related Bug Reports: DOM Storage Support, Live Updates, Create New Items, and Tabbing.

Keyboard Shortcuts #

Keyboard shortcuts are always desired by developers. They can be hard to discover, so here is a complete list and here are the ones that were added recently:

The Scripts Debugger was updated to support some popular keyboard shortcuts:

Related Bug Reports: Switch PanelsDelete Node, Quick Edit, General Debugger Shortcuts and Evaluate Selection.

Cookies #

Viewing Cookie information is now possible under the Storage Panel. Supported platforms show all of the cookies and their hidden information for all domains accessed on the inspected page. Cookie information includes the name, value, path, expiration date, http only flag, and secure (https) flag. Supported platforms may also delete cookies.

If your platform doesn’t have full support you aren’t left in the dark. You will still be able to see the keys and values of the cookies that are accessible via JavaScript on the inspected page.

Inspect Hidden Cookie Information

Related Bug Reports: Initial Support, Hidden Data 1 and 2, Cookies for Sub-Resources, and UI Improvements

Event Listeners #

A new Sidebar Pane has been added to the Elements Panel which displays the registered Event Listeners for the selected node.  The Event Listeners that are shown for the selected node are in the exact order that they are fired through the Capturing and Bubbling phases.  This provides developers with the most accurate and useful information possible.

The user interface shows the registered Event Listeners separated by type. If a node has both “onclick” and “onmouseover” listeners then they will naturally appear in different sections. You can also set your filter preference using the Gear Menu. You can choose to see only the listeners registered on the selected node, or the entire event flow.

Inspect Registered Event Listeners

We are actively looking for UI improvements in this area. So if you have some ideas or feedback please feel free to let us know on this bug report!

Related Bug Reports: Event Listeners.

Syntax Highlighting #

Syntax highlighting enhances readability, makes debugging code easier, and looks really awesome. The Web Inspector now includes syntax highlighting for JSON and CSS.

CSS Syntax Highlighting

CSS Syntax Highlighting even works on the more complex “at-rules” such as @import, @media and @font-face. In addition to supporting the syntax highlighting in the Resources Panel, inline scripts and styles in the Elements Tree Hierarchy are syntax highlighted!

Inline JavaScript and CSS Syntax Highlighting

Related Bug Reports: JSON Highlighting, CSS Highlighting, and Inline Highlighting.

Breakpoints and Watch Expressions #

The Script Debugger continues to become more powerful and more useful.  We already mentioned the keyboard shortcuts above, but there are plenty of other enhancements.

There is a new Breakpoints Sidebar Pane that allows you to easily monitor and work with your breakpoints across all files without the hassle of searching for them.  Each sidebar entry shows the source line and contains a checkbox that allows you to directly enable or disable the breakpoint. Clicking on the entry will jump you directly to the highlighted line in the source file. Finally, deleting a breakpoint has been made easier by clicking the “blue tag” breakpoint indicator.  The tag will cycle through its three states of active, inactive, and removed.

A powerful feature added to the debugger is Conditional Breakpoints. Once you have a breakpoint set, right click on the “blue tag” breakpoint indicator and you will get a popup asking for a conditional statement for that breakpoint. Simply provide an expression and the breakpoint will only pause from then on only if the condition is true.

Breakpoints and other Debugging Improvements

Another new feature in the Debugger is Watch Expressions.  In this new Sidebar Pane you can add any number of expressions that evaluate in the global scope normally but in the local scope when paused in the debugger. Once added you get the full Object Properties tree view of the values of each expression.  These watch expressions automatically refresh when the debugger pauses. They are also persist across page loads.

Watched Expressions in Action

Related Bug Reports: Breakpoints Sidebar PaneWatch Expressions, Evaluate on Breakpoint, Conditional Breakpoints, and Delete Breakpoints.

Debugging AJAX #

An extremely valuable feature for developers working with AJAX is the ability to view the exact parameters and payload sent on XMLHttpRequests.

In the individual resource view there are new sections for viewing submitted Form Data, Query String Parameters, and Request Payloads when appropriate. You can toggle viewing the information in its unencoded (default) and encoded forms with a double-click.

There is also new section named HTTP Information which contains the Request Method (GET, POST, etc.) and the Status Code (200, 404, etc.). Additionally, it adds a colored dot next to the requested URL to show the status (green for success, orange for redirect, and red for error).

View Submitted Form Data and HTTP Information

Related Bug Reports: HTTP Status Code and Data, Parameters, and Payload

Resources and Console Scope Bars #

In order to filter through the Resources or Console messages the Web Inspector now sports some familiar Scope Bars. This has proven to be very useful in the Resources Panel for easily viewing all resources of a particular type.

Quick Filtering Scope Bars for Resources Types and Console Message Types

Related Bug Reports: Resources Scope Bar and Console Scope Bars.

Resources Timeline #

The Web Inspector now specifically shows in the timeline when the DOMContentLoaded and Load events fire. This helps clarify the time it takes for pages to load and helps you improve your websites load times.

DOMContent Ready Event and Page's Load Event Indicators

Related Bug Reports: Show Load Lines

Resources Interactivity #

A couple new features allow you to more directly access individual resources from within the Web Inspector. Instead of copying their URL and opening a new tab manually you can now double-click the Resource in the sidebar to open it directly in a new window. Or, you can drag and drop the resource using HTML5 drag and drop events!

Related Bug Reports: Open Resource Directly and Drag and Drop.

Console Improvements #

Properties in the Web Inspector’s Console are now sorted in a much more natural and useful way. By sorting keys alphanumerically Arrays with greater then 10 elements are much easier to work with.

Alphanumeric Sorting

Another tweak is that collections such as NodeLists and HTMLCollections are now displayed like Arrays.  This meaning that their contents are shown directly in the console, no longer requiring any extra boilerplate.

More Descriptive Nodelists

Related Bug Reports: Sorting and NodeLists.

Firebug Command API Improvements #

More improvements have been made to support more of the Firebug Command Line API. The Web Inspector now supports the inspect() function, which can take an Element, Database, or Storage area and automatically jumps to the appropriate Panel with information. Also, the $0-$4 variables contain the current and previous selected nodes from the Elements Tree Hierarchy.

These command line APIs are usable inside the Web Inspector’s Console. To make working with these APIs even easier, they now show up in the Console’s autocompletion.

Related Bug Reports: $# Variables, inspect() Function, and Autocompletion.

How You Can Contribute #

Many of these new features were added by members of the Open Source Community. We would like to encourage you to contribute as well! Since the Web Inspector itself is mostly HTML, JavaScript, and CSS that means that you already have the skills you need to join in! Interested? Play around right now by inspecting the inspector itself!

Work on the Web Inspector using the Web Inspector!

If you’re interested in contributing and have any questions please stop by the #webkit-inspector IRC channel! As an encouragement to developers, included at the end of each section above are the core bug reports that were involved in bringing each of these features to life.

Finally, if you have ideas for new features, any improvements, or if you’ve stumbled across a bug then please don’t hesitate to create a bug report. This link has pre-populated most of the fields so that you only need to fill out the Summary and Description. As always you should do a quick search through the existing inspector bugs first.

Why do we have an IMG element?

On February 25, 1993, Marc Andreessen wrote:

I’d like to propose a new, optional HTML tag:


Required argument is SRC="url".

This names a bitmap or pixmap file for the browser to attempt to pull over the network and interpret as an image, to be embedded in the text at the point of the tag’s occurrence.

An example is:

<IMG SRC="file://foobar.com/foo/bar/blargh.xbm">

(There is no closing tag; this is just a standalone tag.)

This tag can be embedded in an anchor like anything else; when that happens, it becomes an icon that’s sensitive to activation just like a regular text anchor.

Browsers should be afforded flexibility as to which image formats they support. Xbm and Xpm are good ones to support, for example. If a browser cannot interpret a given format, it can do whatever it wants instead (X Mosaic will pop up a default bitmap as a placeholder).

This is required functionality for X Mosaic; we have this working, and we’ll at least be using it internally. I’m certainly open to suggestions as to how this should be handled within HTML; if you have a better idea than what I’m presenting now, please let me know. I know this is hazy wrt image format, but I don’t see an alternative than to just say “let the browser do what it can” and wait for the perfect solution to come along (MIME, someday, maybe).

Xbm and Xpm were popular graphics formats on Unix systems.

“Mosaic” was one of the earliest web browsers. (“X Mosaic” was the version that ran on Unix systems.) When he wrote this message in early 1993, Marc Andreessen had not yet founded the company that made him famous, Mosaic Communications Corporation, nor had he started work on that company’s flagship product, “Mosaic Netscape.” (You may know them better by their later names, “Netscape Corporation” and “Netscape Navigator.”)

“MIME, someday, maybe” is a reference to content negotiation, a feature of HTTP where a client (like a web browser) tells the server (like a web server) what types of resources it supports (like image/jpeg) so the server can return something in the client’s preferred format. The Original HTTP as defined in 1991 (the only version that was implemented in February 1993) did not have a way for clients to tell servers what kind of images they supported, thus the design dilemma that Marc faced.

A few hours later, Tony Johnson replied:

I have something very similar in Midas 2.0 (in use here at SLAC, and due for public release any week now), except that all the names are different, and it has an extra argument NAME="name". It has almost exactly the same functionality as your proposed IMG tag. e.g.

<ICON name="NoEntry" href="http://note/foo/bar/NoEntry.xbm">

The idea of the name parameter was to allow the browser to have a set of “built in” images. If the name matches a “built in” image it would use that instead of having to go out and fetch the image. The name could also act as a hint for “line mode” browsers as to what kind of a symbol to put in place of the image.

I don’t much care about the parameter or tag names, but it would be sensible if we used the same things. I don’t much care for abbreviations, ie why not IMAGE= and SOURCE=. I somewhat prefer ICON since it imlies that the IMAGE should be smallish, but maybe ICON is an overloaded word?

Midas was another early web browser, a contemporary of X Mosaic. It was cross-platform; it ran on both Unix and VMS. “SLAC” refers to the Stanford Linear Accelerator Center (now the SLAC National Accelerator Laboratory). SLAC hosted the first web server in the United States (in fact the first web server outside Europe). When Tony wrote this message, SLAC was an old-timer on the WWW, having hosted five pages on their web server for a whopping 441 days.

Tony continued:

While we are on the subject of new tags, I have another, somewhat similar tag, which I would like to support in Midas 2.0. In principle it is:


The intention here would be that the second document is to be included into the first document at the place where the tag occured. In principle the referenced document could be anything, but the main purpose was to allow images (in this case arbitrary sized) to be embedded into documents. Again the intention would be that when HTTP2 comes along the format of the included document would be up for separate negotiation.

“HTTP2” is a reference to Basic HTTP as defined in 1992. At this point in early 1993, it was still largely unimplemented. The draft known as “HTTP2” evolved and was eventually standardized as “HTTP 1.0” (albeit not for another three years). HTTP 1.0 did include request headers for content negotiation, a.k.a. “MIME, someday, maybe.”

Tony continued:

An alternative I was considering was:

<A HREF="..." INCLUDE>See photo</A>

I don’t much like adding more functionality to the <A> tag, but the idea here is to maintain compatibility with browsers that can not honour the INCLUDE parameter. The intention is that browsers which do understand INCLUDE, replace the anchor text (in this case “See photo”) with the included document (picture), while older or dumber browsers ignore the INCLUDE tag completely.

This proposal was never implemented, although the idea of text-if-an-image-is-missing is an important accessibility technique which was missing from Marc’s initial <IMG> proposal. Many years later, this feature was bolted on as the <img alt> attribute, which Netscape promptly broke by erroneously treating it as a tooltip.

A few hours after that, Tim Berners-Lee responded:

I had imagined that figues would be reprented as

<a name=fig1 href="fghjkdfghj" REL="EMBED, PRESENT">Figure </a>

where the relation ship values mean

EMBED	 Embed this here when presenting it
PRESENT	 Present this whenever the source document is presented

Note that you can have various combinations of these, and if the browser doesn’t support either one, it doesn’t break.

[I] see that using this as a method for selectable icons means nesting anchors. Hmmm. But I hadn’t wanted a special tag.

This proposal was never implemented, but the rel attribute is still around.

Jim Davis added:

It would be nice if there was a way to specify the content type, e.g.

<IMG HREF="http://nsa.gov/pub/sounds/gorby.au" CONTENT-TYPE=audio/basic>

But I am completely willing to live with the requirement that I specify the content type by file extension.

This proposal was never implemented, but Netscape did later add arbitrary embedding of media objects with the <embed> element.

Jay C. Weber asked:

While images are at the top of my list of desired medium types in a WWW browser, I don’t think we should add idiosyncratic hooks for media one at a time. Whatever happened to the enthusiasm for using the MIME typing mechanism?

Marc Andreessen replied:

This isn’t a substitute for the upcoming use of MIME as a standard document mechanism; this provides a necessary and simple implementation of functionality that’s needed independently from MIME.

Jay C. Weber responded:

Let’s temporarily forget about MIME, if it clouds the issue. My objection was to the discussion of “how are we going to support embedded images” rather than “how are we going to support embedded objections in various media”.

Otherwise, next week someone is going to suggest ‘lets put in a new tag <AUD SRC="file://foobar.com/foo/bar/blargh.snd">‘ for audio.

There shouldn’t be much cost in going with something that generalizes.

With the benefit of hindsight, it appears that Jay’s concerns were well-founded. It took a little more than a week, but HTML5 did finally add new <video> and <audio> elements.

Responding to Jay’s original message, Dave Raggett said:

True indeed! I want to consider a whole range of possible image/line art types, along with the possibility of format negotiation. Tim’s note on supporting clickable areas within images is also important.

Later in 1993, Dave Raggett proposed HTML+ as an evolution of the HTML standard. The proposal was never implemented, and it was superceded by HTML 2.0. HTML 2.0 was a “retro-spec,” which means it formalized features already in common use. “This specification brings together, clarifies, and formalizes a set of features that roughly corresponds to the capabilities of HTML in common use prior to June 1994.”

Dave later wrote HTML 3.0, based on his earlier HTML+ draft. HTML 3.0 was also never implemented (outside of the W3C’s own reference implementation, Arena), and it was superceded by HTML 3.2. HTML 3.2 was also a “retro-spec” — “HTML 3.2 adds widely deployed features such as tables, applets and text flow around images, while providing full backwards compatibility with the existing standard HTML 2.0.”

Dave later co-authored HTML 4.0 and developed HTML Tidy, and went on to help with XHTML, XForms, MathML, and other modern W3C specifications.

Getting back to 1993, Marc replied to Dave:

Actually, maybe we should think about a general-purpose procedural graphics language within which we can embed arbitrary hyperlinks attached to icons, images, or text, or anything. Has anyone else seen Intermedia’s capabilities wrt this?

Intermedia was a hypertext project from Brown University. It was developed from 1985 to 1991 and ran on A/UX, a Unix-like operating system for early Macintosh computers.

The idea of a “general-purpose procedural graphics language” did eventually catch on. Modern browsers support both SVG (declarative markup with embedded scripting) and <canvas> (procedural direct-mode graphics API), although the latter started as a proprietary extension before being “retro-specced” by the WHATWG.

Bill Janssen replied:

Other systems to look at which have this (fairly valuable) notion are Andrew and Slate. Andrew is built with _insets_, each of which has some interesting type, such as text, bitmap, drawing, animation, message, spreadsheet, etc. The notion of arbitrary recursive embedding is present, so that an inset of any kind can be embedded in any other kind which supports embedding. For example, an inset can be embedded at any point in the text of the text widget, or in any rectangular area in the drawing widget, or in any cell of the spreadsheet.

“Andrew” is a reference to the Andrew User Interface System (although at that time it was simply known as the Andrew Project).

Meanwhile, Thomas Fine had a different idea:

Here’s my opinion. The best way to do images in WWW is by using MIME. I’m sure postscript is already a supported subtype in MIME, and it deals very nicely with mixing text and graphics.

But it isn’t clickable, you say? Yes your right. I suspect there is already an answer to this in display postscript. Even if there isn’t the addition to standard postscript is trivial. Define an anchor command which specifies the URL and uses the current path as a closed region for the button. Since postscript deals so well with paths, this makes arbitrary button shapes trivial.

Display Postscript was an on-screen rendering technology co-developed by Adobe and NeXT.

This proposal was never implemented, but the idea that the best way to fix HTML is to replace it with something else altogether still pops up from time to time.

Tim Berners-Lee, March 2, 1993:

HTTP2 allows a document to contain any type which the user has said he can handle, not just registered MIME types. So one can experiment. Yes I think there is a case for postscript with hypertext. I don’t know whether display postcript has enough. I know Adobe are trying to establish their own postscript-based “PDF” which will have links, and be readable by their proprietory brand of viewers.

I thought that a generic overlaying language for anchors (Hytime based?) would allow the hypertext and the graphics/video standards to evolve separately, which would help both.

Let the IMG tag be INCLUDE and let it refer to an arbitrary document type. Or EMBED if INCLUDE sounds like a cpp include which people will expect to provide SGML source code to be parsed inline — not what was intended.

HyTime was an early, SGML-based hypertext document system. It loomed large in many early discussions of HTML, and later XML.

Tim’s proposal for an <INCLUDE> tag was never implemented, although you can see echoes of it in <object>, <embed>, and the <iframe> element.

Finally, on March 12, 1993, Marc Andreessen revisited the thread:

Back to the inlined image thread again — I’m getting close to releasing Mosaic v0.10, which will support inlined GIF and XBM images/bitmaps, as mentioned previously. …

We’re not prepared to support INCLUDE/EMBED at this point. … So we’re probably going to go with <IMG SRC="url"> (not ICON, since not all inlined images can be meaningfully called icons). For the time being, inlined images won’t be explicitly content-type’d; down the road, we plan to support that (along with the general adaptation of MIME). Actually, the image reading routines we’re currently using figure out the image format on the fly, so the filename extension won’t even be significant.

I don’t really know why I wrote this. It wasn’t what I set out to write. That happens. But I am extraordinarily fascinated with all aspects of this almost-17-year-old conversation. Consider:

But none of this answers the original question: why do we have an <img> element? Why not an <icon> element? Or an <include> element? Why not a hyperlink with an include attribute, or some combination of rel values? Why an <img> element? Quite simply, because Marc Andreessen shipped one, and shipping code wins.

That’s not to say that all shipping code wins; after all, Andrew and Intermedia and HyTime shipped code too. Code is necessary but not sufficient for success. And I certainly don’t mean to say that shipping code before a standard will produce the best solution. Marc’s <img> element didn’t mandate a common graphics format; it didn’t define how text flowed around it; it didn’t support text alternatives or fallback content for older browsers. And 16, almost 17 years later, we’re still struggling with content sniffing, and it’s still a source of crazy security vulnerabilities. And you can trace that all the way back, 17 years, through the Great Browser Wars, all the way back to February 25, 1993, when Marc Andreessen offhandedly remarked, “MIME, someday, maybe,” and then shipped his code anyway.

The ones that win are the ones that ship.

YUI Theater — Brendan Eich: “ECMA Harmony and the Future of JavaScript”

Brendan Eich of Mozilla at YUICONF 2009, held at the Yahoo! HQ in Sunnyvale; October 28, 2009.

Brendan Eich, JavaScript’s creator, gave the opening-night keynote at last week’s YUICONF 2009. His talk, “ECMA Harmony and the Future of JavaScript,” related some of the technical, corporate and social processes that have marked the recent history of the language. It’s a fascinating story. As the next release of ECMAScript (now ECMAScript 5.0) comes up for a vote in December, there remains some dissent, with IBM still indicating discomfort. But the prospect of ECMAScript moving ahead to a new version looks increasingly plausible. Brendan’s perspective on this is both strikingly open and deeply committed. Our thanks to him for the talk and for allowing us to share it here.

If the video embed below doesn’t show up correctly in your RSS reader of choice, be sure to click through to watch the high-resolution version of the video on YUI Theater; the downloadable version is much smaller, optimized as it is for iPods, iPhones, and other handheld devices.

Other Recent YUI Theater Videos:

Subscribing to YUI Theater:

StatCounter and Net Applications market share numbers compared to actual numbers

Google just announced that Chrome has more than 30 million users. The latest number for Opera from a few months ago was more than 40 million users. However, both StatCounter and Net Applications list Chrome with a higher market share than Opera in October (1.88 for Opera/4.17 for Chrome, and 2.17 for Opera/3.58 for Chrome, respectively).

That's how reliable browser statistics are...

A quote from Matt Palmer

I loathe [hardware load balancers]. They’re expensive, restrictive, slow, and generally cause you a lot more pain and suffering than they’re worth. At my last job, one of my projects was to convert most of one of our existing clusters from a load-balancing appliance to use keepalived. Why would we do this? Because the $100k worth of appliance wasn’t capable of doing the job that $15k worth of commodity hardware and an installation of keepalived were handling with ease.

- Matt Palmer

Jeremy Zawodny: WebSequenceDiagrams.com - Create sequence diagrams in seconds

Jeremy Zawodny
WebSequenceDiagrams.com - Create sequence diagrams in seconds - http://www.websequencediagrams.com/
arty, Vishy, Cliff Gerrish and ǝuǝƃnǝ liked this
that's a really handy tool! - Jeremy Zawodny

Adam Bosworth: “All successful standards are as simple as possible, not as hard as possible.”

Adam Bosworth: “All successful standards are as simple as possible, not as hard as possible.” Required reading.

Need to hire a really great programmer? Want a job that doesn't drive you crazy? Visit the Joel on Software Job Board: Great software jobs, great people.

← предыдущий месяц