13 нояб. 2018 г.

Chrome DevTools tips and tricks


  • $0 в консоли - ссылка на на текущий выбранный элемент в панели элементов (Elements)
  • $_ в консоли - ссылка на последний вычисленный в консоли результат
  • Ctrl-click (Cmd-click в MacOS) по правилу CSS в панели элементов - Chrome DevTools откроет определение этого стиля в панели Sources
  • Ctrl-Shift-P (Cmd-Shift-P в MacOS) - быстрый поиск команд
  • Chrome умеет делать скриншоты: Ctrl-Shift-P - набрать screenshot - есть команды Capture screenshot, Capture node screenshot, Capture full size screenshot
  • Поиск в панели элементов (Ctrl-F) можно вести по строке, CSS-селектору или XPath
  • Ctrl-Shift-O - навигация по списку имён в текущем файле (классы, функции и т.п.)
  • Ctrl-O (Cmd-O, Cmd-P) в панели Sources - универсальная навигация: по списку всех загруженных файлов, по номерам строк в текущем файле, по символам в текущем файле, по командам DevTools
  • Alt-click в MacOS (Alt- или Ctrl-Alt-click в Windows) по треугольнику слева от элемента в панели элементов - развернуть элемент и все вложенные в него элементы
  • Ctrl-Shift-D - изменение docking mode (расположения) DevTools - сбоку, снизу или в отдельном окне
  • Выделение мышкой с нажатой Alt в панелях Elements и Sources - выделение вертикального блока (Esc - вернуться к обычному одиночному курсору)
  • Если навести мышку на селектор в стилях в панели элементов и подождать - Chrome подсветит на странице все элементы с таким селектором
  • В контекстном меню для каждого запроса в панели Network есть пункты Copy as fetch, Copy as cURL - в буфер будет скопирована команда JavaScript или команда curl с правильными параметрами
  • В контекстном меню для каждого запроса в панели Network есть возможность заблокировать загрузку данного ресурса
  • Ctrl-Shift-F (Cmd-Alt-F) в консоли - поиск строки сразу во всех доступных файлах
  • copy(object) в консоли копирует переданный объект как строку в буфер обмена
  • queryObjects(Array) в консоли покажет все объекты, созданные конструктором Array

1 окт. 2018 г.

Визуализация результатов профилирования в chrome://tracing

При профилировании сложных библиотек и фреймворков типа React и Angular в полученных результатах очень много визуального шума от всевозможных обёрток и утилитных функций, которые загромождают стек. Можно и нужно сделать свой собственный код для более высокоуровневого профилирования (например, в React замерять только времена стандартных методов жизненного цикла компонента: shouldComponentUpdate, render и т.д.).

Встаёт вопрос визуализации полученных данных. Таблички - хорошо, но таймлайн или flame chart - нагляднее и легче для анализа. Можно быстро набросать визуализатор с помощью Google Charts Timeline, но хочется чего-то более мощного и интерактивного, как в Dev tools, с возможностью масштабирования и перемещения вдоль временной оси.

1 июл. 2018 г.

21 мая 2018 г.

Background tab in Chrome browser: how it affects JS

This presentation from Chrome developers shows technical details regarding what happens to a web page when it goes into background (the user switches to another tab)

Freezing:

  • ~2013: timers are stopped on mobile after 5 minutes
  • M67: loading tasks are stopped on mobile after 5 minutes
  • M68 (experiment): page is frozen on desktop after 1 hour without network activity
  • M69: page will be frozen or discarded based on the API it uses
  • ~2020: page will be frozen after loading
Throttling:
  • 2011: setTimeout/setInterval are fired once a second
  • M56: timers are delayed to limit CPU usage to 1%
  • M68: workers are throttled
  • 2018: non-timer tasks are throttled
  • ~2020: page will be throttled during loading depending on the foreground activity

23 мар. 2018 г.

Frequently forgotten limitations of the :visited link selector


  • Sibling selectors like :visited + span don't work in CSS
  • Nested selectors like :visited div don't work in CSS
  • :visited link can be styled only via
    • color
    • background-color
    • border-color
    • column-rule-color
    • outline-color
    • fill (color only)
    • stroke (color only)
  • You cannot change the transparency of the above mentioned allowed rules via color: rgba() or similar techniques, i.e.
    a {color: rgba(128, 0, 0, 0.5)} a:visited {color: rgba(0, 128, 0, 0.1)}
    is effectively equal to
    a {color: rgba(128, 0, 0, 0.5)} a:visited {color: rgba(0, 128, 0, 0.5)}
  • window.getComputedStyle, element.querySelector etc. won't detect :visited link



Reference to the MDN documentation page: https://developer.mozilla.org/en-US/docs/Web/CSS/Privacy_and_the_:visited_selector

6 февр. 2018 г.

24 янв. 2018 г.

Don't forget to test your web site/application in private browsing (incognito) mode

From time to time one or another web site or web application (SPA, PWA whatever word is now trendy) faces that problem: it throws errors and does not work when private browsing mode is turned on. Real-world examples: Google+ signinAmazon Cognito Identity SDK.

Here is more-or-less correct and complete list of things that don't work when private browsing (incognito mode) is turned on:
  • Safari 10 and below: localStorage and sessionStorage API is present, but throws a DOMException.QUOTA_EXCEEDED_ERR when the code is trying to write something. Fixed in Safari 11
  • IE10+/Edge: indexedDB is undefined
  • Firefox: indexedDB is undefined
A similar situation may happen when the user has disabled cookies/data, e.g. in Chrome/Chromium: Settings -> "Show advanced settings..." -> "Content settings..." -> "Block sites from setting any data".
  • Chrome/Chromium: cookies, localStorage, sessionStorage and indexedDB are disabled. Will throw "Uncaught SecurityError: Access to 'localStorage' is denied for this document".
  • Firefox: cookies, localStorage, sessionStorage
  • IE: cookies
And one more restriction exists in Safari when JavaScript is in strict mode: modification of error object may be forbidden (both overwriting existing property and adding a new one) and may throw

10 янв. 2018 г.

How to write to NTFS USB drives on Mac OS X

Mac OS X by default can only read from attached USB drives with the NTFS file system. Here are the steps to enable read/write access:


Initial setup (only first time on a new Mac)

  1. Install Homebrew (and probably additional XCode tools)
  2. In Terminal: brew install caskroom/cask/osxfuse
  3. In Terminal: brew install ntfs-3g
  4. In Terminal: sudo mkdir -p /Volumes/NTFS

Each time when an NTFS USB drive is connected to the computer

  1. List disk partitions: diskutil list
  2. Find identifier of the partition with Windows_NTFS type (typically disk2s1 or disk3s1)
  3. Unmount found drive: sudo umount /dev/disk2s1
  4. Mount the drive with read/write access: sudo ntfs-3g /dev/disk2s1 /Volumes/NTFS -olocal -oallow_other
  5. The mounted drive should appear on the desktop, the file system should be mounted at /Volumes/NTFS.

The same steps in a shell script


sudo mkdir -p /Volumes/NTFS
DISK=`diskutil list | grep Windows_NTFS | sed -E "s/.+Windows_NTFS .+ GB +//"`
echo Mounting NTFS disk $DISK
sudo umount /dev/$DISK
sudo ntfs-3g /dev/$DISK /Volumes/NTFS -olocal -oallow_other

8 янв. 2018 г.

Proper transition: transform CSS for Android 4.4 browser, Chrome and Safari

Suppose you want CSS transitions for CSS "transform" property on mobile devices (Android 4.4 and above, iOS Safari 7 and above). You'd write

.example {
    transition: transform 1s ease;
}

But what about browser support for CSS 2D transforms and 3D transforms? They require "-webkit-" vendor prefix. No problem, you just add another line

.example {
    transition: -webkit-transform 1s ease;
    transition: transform 1s ease;
}

Stop. That won't work: the former rule is overridden by latter. OK, then combine them into one rule. Browsers should either ignore unknown transition property or use transition for both:

.example {
    transition: transform 1s ease, -webkit-transform 1s ease;
}

Surprise! Safari 7.X (and probably 8.X) doesn't comply to the specification and ignores the whole rule, not only the unknown "transform" property. The only way to write transition cross-browser is

.example {
    transition: -webkit-transform 1s ease;                    /* 1 */
    transition: transform 1s ease;                            /* 2 */
    transition: transform 1s ease, -webkit-transform 1s ease; /* 3 */
}

Let's analyze it with regard to intended browser support:

  • Safari 7.X and 8.X will accept rule 1 and ignore the rest because of unknown "transform" property. That's fine - they will use transition for the "-webkit-transform".
  • The same applies to WebKit-based browsers in Android 4.4
  • Chrome and Safari 9+ will accept rule 1, then override it with rule 2, then override it with rule 3. That's fine too - they will use transition for both prefixed and unprefixed transforms.
The easiest way to avoid such traps is to use Autoprefixer to automatically add vendor prefixes to CSS rules.