├── .editorconfig ├── .gitignore ├── README.md ├── article.txt ├── babel.config.js ├── gh-pages-deploy.js ├── package-lock.json ├── package.json ├── public ├── favicon.ico └── index.html ├── src ├── App.vue ├── assets │ └── main.sass ├── components │ ├── HeavyItem.vue │ ├── Item.vue │ ├── ItemWithRename.vue │ ├── ItemWithRenameById1.vue │ ├── ItemWithRenameById2.vue │ └── Tiger.vue ├── directives │ ├── NodeIntersect.js │ └── NodeIntersect.ts ├── main.js ├── router │ ├── index.js │ └── routes.js ├── store │ ├── example1.js │ ├── example2.js │ ├── example3.js │ ├── example4.js │ └── index.js └── views │ ├── Example1.vue │ ├── Example2.vue │ ├── Example3.vue │ ├── Example4p1.vue │ ├── Example4p2.vue │ ├── Example4p3.vue │ ├── Example5.vue │ ├── Examples.vue │ └── Home.vue └── vue.config.js /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.{js,jsx,ts,tsx,vue}] 2 | indent_style = space 3 | indent_size = 2 4 | trim_trailing_whitespace = true 5 | insert_final_newline = true 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /dist 4 | 5 | 6 | # local env files 7 | .env.local 8 | .env.*.local 9 | 10 | # Log files 11 | npm-debug.log* 12 | yarn-debug.log* 13 | yarn-error.log* 14 | pnpm-debug.log* 15 | 16 | # Editor directories and files 17 | .idea 18 | .vscode 19 | *.suo 20 | *.ntvs* 21 | *.njsproj 22 | *.sln 23 | *.sw? 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rerendering-article-vue2 2 | 3 | ## Project setup 4 | ``` 5 | npm install 6 | ``` 7 | 8 | ### Compiles and hot-reloads for development 9 | ``` 10 | npm run serve 11 | ``` 12 | 13 | ### Compiles and minifies for production 14 | ``` 15 | npm run build 16 | ``` 17 | 18 | ### Lints and fixes files 19 | ``` 20 | npm run lint 21 | ``` 22 | 23 | ### Customize configuration 24 | See [Configuration Reference](https://cli.vuejs.org/config/). 25 | -------------------------------------------------------------------------------- /article.txt: -------------------------------------------------------------------------------- 1 | Улучшение производительности vue приложения 2 | 3 | У нас в TeamHood есть wiki. 4 | Там собралась коллекция рекоммендаций, в том числе, по улучшению производительности тяжелого фронтенда на vue.js. 5 | Улучшать производительность понадобилось, потому что в силу специфики наши основные экраны не имеют пагинации. 6 | Есть клиенты, у которых на одной kanban/gantt-доске больше тысячи вот таких вот карточек, все это должно работать без лагов. 7 | 8 | [img] 9 | - 2 rows 10 | - development board 11 | - subtasks + in progress, for pairtest 12 | -- resort rows; 13 | -- move task with 3 children to parent-child column 14 | -- assign first child 15 | -- resort children 16 | -- trigger submenu, assign a tag 17 | -- mark third child completed 18 | 19 | В статье разобрано несколько редко упоминаемых техник из нашей wiki, которые помогут сократить излишний рендеринг компонентов и улучшить производительность. 20 | 21 | https://kasheftin.github.io/vue-rerendering-optimization/ 22 | https://github.com/Kasheftin/vue-rerendering-optimization 23 | 24 | Все примеры собраны в отдельном репозитории [link]. Это vue2 приложение, хотя все проверено и продолжает быть актуальным для vue3. 25 | По моему мнению, vue3 еще не production-ready. В vuex4 утекает память, исследовать соответствующие оптимизации там пока бессмысленно (что обнадеживает, затраты памяти там в разы меньше чем в vue2+vuex3). 26 | Примеры написаны на минимальном простейшем javascript, было искушение воткнуть vue-class-component, typescript, typed-vuex и остальную кухню реального проекта, но удержался. 27 | 28 | 1. (Deep) Object Watchers. 29 | Не использовать deep модификатор; использовать watch только для примитивных типов. 30 | Начнем с простого примера. 31 | Некий массив items приходит с сервера, сохраняется в vuex store, отрисовывается, возле каждого item есть чекбокс. 32 | Свойство isChecked относится к интерфейсу, хранится отдельно от item, однако есть getter, который собирает их вместе: 33 | 34 | ```` 35 | export const state = () => ({ 36 | items: [{ id: 1, name: 'First' }, { id: 2, name: 'Second' }], 37 | checkedItemIds: [1, 2] 38 | }) 39 | 40 | export const getters = { 41 | extendedItems (state) { 42 | return state.items.map(item => ({ 43 | ...item, 44 | isChecked: state.checkedItemIds.includes(item.id) 45 | })) 46 | } 47 | } 48 | ```` 49 | 50 | Допустим, items могут быть отсортированы пользователем, и мы хотим сохранять порядок. Что-то вроде: 51 | 52 | ```` 53 | export default class ItemList extends Vue { 54 | computed: { 55 | extendedItems () { return this.$store.getters.extendedItems }, 56 | itemIds () { return this.extendedItems.map(item => item.id) } 57 | }, 58 | watch: { 59 | itemIds () { 60 | console.log('Saving new items order...', this.itemIds) 61 | } 62 | } 63 | } 64 | ```` 65 | 66 | В этом случае переключение чекбокса у любого item вызывается излишнее срабатывание сохранение порядка. 67 | Конструирование новых объектов - настолько естественный процесс, что даже в этом тривиальном примере мы делаем это дважды. 68 | Изменение checkedItemIds вызвает пересоздание массива extendedItems (и пересоздание каждого элемента этого массива), затем 69 | идет пересоздание объекта itemIds. Это может казаться контра-интуитивным, ведь создается массив, состоящий из тех же самых элементов в том же самом порядке. 70 | Однако, это природа javascript, [1,2,3] != [1,2,3]. 71 | 72 | Решение - полный отказ от использования watcher для объектов и массивов. 73 | Для каждого сложного watcher создается отдельный computed примитивного типа. 74 | Например, если требуется отслеживать свойства {id, title, userId} в массиве items, можно сделать строку, 75 | 76 | ```` 77 | computed: { 78 | itemsTrigger () { return JSON.stringify(items.map(item => ({ id: item.id, title: item.title, userId: item.userId }))) } 79 | }, 80 | watch: { 81 | itemsTrigger () { 82 | // Здесь не нужен JSON.parse - дешевле пользоваться исходным this.items; 83 | } 84 | } 85 | ```` 86 | 87 | Очевидно, чем точнее условие для срабатывания watcher, тем лучше, тем точнее он срабатывает. 88 | Объектный watcher - плохо, deep watcher - еще хуже. 89 | Использование deep в коде - частый признак неграмотности разработчика. 90 | Типа я не понимаю что делает этот код, какими объектами он оперирует, но что-то иногда не срабатывает, навешу-ка я deep - о вроде работает. 91 | Это что-то уровня.. (был у меня и такой проект).. в компоненте не срабатывала реактивность, и вместо того, чтобы найти ошибку, был повешен $emit('reinit'), 92 | по которому родительский компонент убивал данный и создавал его заново в $nextTick. 93 | Все это забавно мигало. 94 | 95 | 2. Ограничение реактивности (freeze). 96 | Использование Object.freeze на проекте TeamHood внезапно сократило потребление памяти в 2 раза. 97 | 98 | [Image before - after] 99 | 100 | Однако оно даже больше относится к моему второму основному проекту, StarBright, где используется nuxt и серверный рендеринг. 101 | Nuxt подразумевает, что некоторые запросы будут отрабатываться на сервере заранее. 102 | Ответы сохраняются в vuex store (и потом используются на клиенте). 103 | Таким образом, всю логику работы с запросами и кешированием данных удобнее держать в vuex. 104 | Компонент делает this.$store.dispatch('fetch', ...), а vuex отдает кеш или делает запрос. 105 | Следовательно, в vuex может содержаться большой объем данных. 106 | Например, пользователь вводил адрес, autocomplete загрузил массив городов, который был закеширован в store с целью избежать повторной загрузки. 107 | Данные статичны, однако vue по умолчанию делает реактивным каждое свойство каждого объекта (рекурсивно). 108 | Во многих случаях это приводит к высокому расходу памяти, и лучше пожертвовать реактивностью отдельных свойств. 109 | Вместо: 110 | 111 | ```` 112 | state: () => ({ 113 | items: [] 114 | }), 115 | mutations: { 116 | setItems (state, items) { 117 | state.items = items 118 | }, 119 | markItemCompleted (state, itemId) { 120 | const item = state.items.find(item => item.id === itemId) 121 | if (item) { 122 | item.completed = true 123 | } 124 | } 125 | } 126 | ```` 127 | 128 | Делаем 129 | 130 | ```` 131 | state: () => ({ 132 | items: [] 133 | }), 134 | mutations: { 135 | setItems (state, items) { 136 | state.items = items.map(item => Object.freeze(item)) 137 | }, 138 | markItemCompleted (state, itemId) { 139 | const itemIndex = state.items.find(item => item.id === itemId) 140 | if (itemIndex !== -1) { 141 | // Не получится делать item.completed = true (объект заморожен), нужно пересоздать весь объект; 142 | const newItem = { 143 | ...state.items[itemIndex], 144 | completed: true 145 | } 146 | state.items.splice(itemIndex, 1, Object.freeze(newItem)) 147 | } 148 | } 149 | } 150 | 151 | Замечу, что замерять расход памяти нужно на build-версии (не в development). 152 | 153 | 3. Функциональные геттеры. 154 | Иногда это пропускают в документации (https://vuex.vuejs.org/guide/getters.html#method-style-access). 155 | Функциональные геттеры не кешируются. Вот это: 156 | ```` 157 | // Vuex: 158 | getters: { 159 | itemById: (state) => (itemId) => state.items.find(item => item.id === itemId) 160 | } 161 | ... 162 | // Some component: 163 | computed: { 164 | item () { return this.$store.getters.itemById(this.itemId) } 165 | } 166 | ```` 167 | будет делать items.find для каждого компонента . 168 | Вот это: 169 | ```` 170 | getters: { 171 | itemByIds: (state) => state.items.reduce((out, item) => { 172 | out[item.id] = item 173 | return out 174 | }, {}) 175 | } 176 | // Some component: 177 | computed: { 178 | item () { return this.$store.getters.itemsByIds[this.itemId] } 179 | } 180 | ```` 181 | выполнит itemsByIds при первом обращении и закеширует результат. Таким образом, функциональные геттеры не имеют никаких преимуществ перед обычными методами/функциями. 182 | 183 | 4. Грамотное распределение на компоненты. 184 | Компоненты - ключевая часть экосистемы vue. 185 | Понимание жизненного цикла и критериев обновления (shouldComponentUpdate) необходимо для строительства эффективного приложения. 186 | Первое знакомство с компонентами проходит на интуитивно-логическом уровне: есть какие-то однотипные контейнеры, тогда наверное для контейнера лучше сделать отдельный компонент. 187 | Однако, кроме смыслового значения, компоненты - это мощный механизм, дающий контроль над гранулярностью обновлений, это штука, напрямую влияющая на производительность. 188 | Для примера возьмем itemByIds getter из предыдущего пункта и рассмотрим такой код: 189 | ```` 190 | // App.vue 191 | 217 | 218 | Но это не поможет. vue вызывает обновление компонента, если его зависимости меняются. При изменении любого свойства любого item пересоздается 219 | объект itemsByIds, каждый элемент которого - это новый объект { ...item, isChecked: .. }, а поскольку {...item} !== {...item}, идет ререндеринг. 220 | 221 | Каждый vue компонент - это функция, которая отдает virtual DOM и кеширует его (memoization). 222 | Входные аргументы функции - зависимости - отлеживаются на этапе dry run и состоят из ссылок на переменные в props и $store. 223 | Если входной аргумент - поэлементно равный предыдущему новый объект, кеширование не срабатывает. 224 | 225 | Есть два варианта, как это победить - глупый и умный. Очевидно, если сделать 256 | 257 | Демонстрация правильной работы: пример 1, пример 2. 258 | 259 | 5. Применение Intersection Observer. 260 | Отрисовка большого DOM-дерева тормозит сама по себе. Мы применяем несколько техник для оптимизации. 261 | Например, на gantt схемах размеры и положения блоков заранее расчитаны, поэтому известно, что попадает в viewport. Невидимые элементы не отрисовываются. 262 | В других случаях размеры заранее неизвестны, тогда можно применить этот простой прием с intersection observer. 263 | В vuetify есть v-intersect директива, которая работает из коробки, однако она создает отдельный IntersectionObserver на каждый свой биндинг, поэтому не подходит для случая, когда объектов много. 264 | Вот пример, который будем оптимизировать. Там 100 элементов (на экране помещается 10), в каждом мигает тяжелая картинка, замеряется задержка между реальным миганием и расчетным. 265 | Создадим один экземпляр IntersectionObserver и пробросим его через директиву во все узлы, которые он будет отслеживать. 266 | Все, что нужно от директивы - добавиться в IntersectionObserver и запомнить это: 267 | 268 | export default { 269 | inserted (el, { value: observer }) { 270 | if (observer instanceof IntersectionObserver) { 271 | observer.observe(el) 272 | } 273 | el._intersectionObserver = observer 274 | }, 275 | update (el, { value: newObserver }) { 276 | const oldObserver = el._intersectionObserver 277 | const isOldObserver = oldObserver instanceof IntersectionObserver 278 | const isNewObserver = newObserver instanceof IntersectionObserver 279 | if (!isOldObserver && !isNewObserver) || (isOldObserver && (oldObserver === newObserver)) { 280 | return false 281 | } 282 | if (isOldObserver) { 283 | oldObserver.unobserve(el) 284 | el._intersectionObserver = undefined 285 | } 286 | if (isNewObserver) { 287 | newObserver.observe(el) 288 | el._intersectionObserver = newObserver 289 | } 290 | }, 291 | unbind (el) { 292 | if (el._intersectionObserver instanceof IntersectionObserver) { 293 | el._intersectionObserver.unobserve(el) 294 | } 295 | el._intersectionObserver = undefined 296 | } 297 | } 298 | 299 | Теперь известно, какие элементы списка не видны, вопрос, как их облегчать. 300 | Можно, например, менять тяжелый компонент на легкую заглушку или убирать какие-то части. 301 | Однако важно понимать, что сложный компонент сложно отрисовывать. 302 | При быстром скролинге список затупит из-за большого количества инициализаций и деинициализаций. 303 | Практика показывает, что хорошо работает скрытие на уровне css: 304 | 305 | 315 | 316 | 337 | 338 | 342 | 343 | Рабочий пример: example5. 344 | 345 | Ссылки: 346 | - Исходный код примеров; 347 | - Демо; 348 | - Caution using watchers for objects in Vue https://codeburst.io/caution-using-watchers-for-objects-in-vue-ecafb0af6493; 349 | - Vuex4 memory leak issue; -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | '@vue/cli-plugin-babel/preset' 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /gh-pages-deploy.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-console */ 2 | const execa = require("execa"); 3 | const fs = require("fs"); 4 | (async () => { 5 | try { 6 | await execa("git", ["checkout", "--orphan", "gh-pages"]); 7 | // eslint-disable-next-line no-console 8 | console.log("Building started..."); 9 | await execa("npm", ["run", "build"]); 10 | // Understand if it's dist or build folder 11 | const folderName = fs.existsSync("dist") ? "dist" : "build"; 12 | await execa("git", ["--work-tree", folderName, "add", "--all"]); 13 | await execa("git", ["--work-tree", folderName, "commit", "-m", "gh-pages"]); 14 | console.log("Pushing to gh-pages..."); 15 | await execa("git", ["push", "origin", "HEAD:gh-pages", "--force"]); 16 | await execa("rm", ["-r", folderName]); 17 | await execa("git", ["checkout", "-f", "master"]); 18 | await execa("git", ["branch", "-D", "gh-pages"]); 19 | console.log("Successfully deployed, check your settings"); 20 | } catch (e) { 21 | // eslint-disable-next-line no-console 22 | console.log(e.message); 23 | process.exit(1); 24 | } 25 | })(); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rerendering-article-vue2", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "serve": "vue-cli-service serve", 7 | "build": "vue-cli-service build", 8 | "lint": "vue-cli-service lint" 9 | }, 10 | "dependencies": { 11 | "core-js": "^3.6.5", 12 | "uniqid": "^5.2.0", 13 | "vue": "^2.6.11", 14 | "vue-dragscroll": "^2.1.3", 15 | "vue-router": "^3.2.0", 16 | "vuedraggable": "^2.24.3", 17 | "vuex": "^3.4.0" 18 | }, 19 | "devDependencies": { 20 | "@vue/cli-plugin-babel": "~4.5.0", 21 | "@vue/cli-plugin-eslint": "~4.5.0", 22 | "@vue/cli-plugin-router": "~4.5.0", 23 | "@vue/cli-plugin-vuex": "~4.5.0", 24 | "@vue/cli-service": "~4.5.0", 25 | "@vue/eslint-config-standard": "^5.1.2", 26 | "babel-eslint": "^10.1.0", 27 | "eslint": "^6.7.2", 28 | "eslint-plugin-import": "^2.20.2", 29 | "eslint-plugin-node": "^11.1.0", 30 | "eslint-plugin-promise": "^4.2.1", 31 | "eslint-plugin-standard": "^4.0.0", 32 | "eslint-plugin-vue": "^6.2.2", 33 | "sass": "^1.26.5", 34 | "sass-loader": "^8.0.2", 35 | "vue-template-compiler": "^2.6.11" 36 | }, 37 | "eslintConfig": { 38 | "root": true, 39 | "env": { 40 | "node": true 41 | }, 42 | "extends": [ 43 | "plugin:vue/essential", 44 | "@vue/standard" 45 | ], 46 | "parserOptions": { 47 | "parser": "babel-eslint" 48 | }, 49 | "rules": {} 50 | }, 51 | "browserslist": [ 52 | "> 1%", 53 | "last 2 versions", 54 | "not dead" 55 | ] 56 | } 57 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Kasheftin/vue-rerendering-optimization/3e937c52cdb140fdc9978251af43ffb02fa3f4fd/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | <%= htmlWebpackPlugin.options.title %> 9 | 10 | 11 | 14 |
15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/App.vue: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /src/assets/main.sass: -------------------------------------------------------------------------------- 1 | h1 2 | text-align: center 3 | line-height: 2rem 4 | 5 | h3 6 | margin: 20px 0 5px 0 7 | 8 | a 9 | color: #42b983 10 | 11 | @keyframes highlight 12 | 0% 13 | background-color: #ee39 14 | 100% 15 | background-color: none 16 | 17 | body 18 | overflow: hidden 19 | 20 | .rr-dragscroll-container 21 | position: fixed 22 | top: 0 23 | right: 0 24 | bottom: 0 25 | left: 0 26 | overflow: auto 27 | 28 | .rr-app 29 | font-family: Avenir, Helvetica, Arial, sans-serif 30 | -webkit-font-smoothing: antialiased 31 | -moz-osx-font-smoothing: grayscale 32 | color: #2c3e50 33 | margin: 60px auto 0 34 | max-width: 600px 35 | line-height: 1.5em 36 | 37 | .rr-item 38 | border: 1px solid #dedede 39 | padding: 10px 40 | margin: 0 10px 41 | display: flex 42 | align-items: center 43 | &--multiline 44 | display: block 45 | &--highlight 46 | animation: highlight 1s 47 | &__check 48 | margin: 0 10px 0 0 49 | display: flex 50 | align-items: center 51 | &__image 52 | flex: 0 0 100px 53 | &__text 54 | flex: 1 1 auto 55 | 56 | .rr-intersectionable.rr-intersectionable--invisible .rr-item__svg 57 | display: none 58 | 59 | -------------------------------------------------------------------------------- /src/components/HeavyItem.vue: -------------------------------------------------------------------------------- 1 | 16 | 17 | 66 | -------------------------------------------------------------------------------- /src/components/Item.vue: -------------------------------------------------------------------------------- 1 | 16 | 17 | 37 | -------------------------------------------------------------------------------- /src/components/ItemWithRename.vue: -------------------------------------------------------------------------------- 1 | 18 | 19 | 37 | -------------------------------------------------------------------------------- /src/components/ItemWithRenameById1.vue: -------------------------------------------------------------------------------- 1 | 18 | 19 | 38 | -------------------------------------------------------------------------------- /src/components/ItemWithRenameById2.vue: -------------------------------------------------------------------------------- 1 | 18 | 19 | 41 | -------------------------------------------------------------------------------- /src/components/Tiger.vue: -------------------------------------------------------------------------------- 1 | 727 | -------------------------------------------------------------------------------- /src/directives/NodeIntersect.js: -------------------------------------------------------------------------------- 1 | const setObserver = (el, observer, onIntersect) => { 2 | el._intersectionObserver = observer 3 | el._onIntersect = onIntersect 4 | } 5 | 6 | const extractOptions = (options) => { 7 | let observer 8 | let onIntersect 9 | if (options instanceof IntersectionObserver) { 10 | observer = options 11 | } else if (options && typeof options === 'object' && Object.prototype.hasOwnProperty.call(options, 'observer') && options.observer instanceof IntersectionObserver) { 12 | observer = options.observer 13 | if (Object.prototype.hasOwnProperty.call(options, 'onIntersect') && options.onIntersect instanceof Function) { 14 | onIntersect = options.onIntersect 15 | } 16 | } 17 | return { observer, onIntersect } 18 | } 19 | 20 | export default { 21 | inserted (el, { value: options }) { 22 | const { observer, onIntersect } = extractOptions(options) 23 | if (observer instanceof IntersectionObserver) { 24 | observer.observe(el) 25 | } 26 | setObserver(el, observer, onIntersect) 27 | }, 28 | update (el, { value: newOptions }) { 29 | const { observer: newObserver, onIntersect: newOnIntersect } = extractOptions(newOptions) 30 | const oldObserver = el._intersectionObserver 31 | const isOldObserver = oldObserver instanceof IntersectionObserver 32 | const isNewObserver = newObserver instanceof IntersectionObserver 33 | 34 | if (!isOldObserver && !isNewObserver) { 35 | return false 36 | } 37 | 38 | if (isOldObserver && isNewObserver && (oldObserver === newObserver)) { 39 | setObserver(el, newObserver, newOnIntersect) 40 | return false 41 | } 42 | 43 | if (oldObserver && isOldObserver) { 44 | oldObserver.unobserve(el) 45 | setObserver(el, undefined, undefined) 46 | } 47 | 48 | if (newObserver && isNewObserver) { 49 | newObserver.observe(el) 50 | setObserver(el, newObserver, newOnIntersect) 51 | } 52 | }, 53 | unbind (el) { 54 | const cached = el._intersectionObserver 55 | if (cached instanceof IntersectionObserver) { 56 | cached.unobserve(el) 57 | } 58 | setObserver(el, undefined, undefined) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/directives/NodeIntersect.ts: -------------------------------------------------------------------------------- 1 | import { DirectiveBinding } from 'vue/types/options' 2 | 3 | type onIntersectFunction = (isIntersecting: boolean) => void 4 | 5 | interface HTMLBaseElementWithObserver extends HTMLBaseElement { 6 | _intersectionObserver?: IntersectionObserver 7 | _onIntersect?: onIntersectFunction 8 | } 9 | 10 | const setObserver = (el: HTMLBaseElementWithObserver, observer?: IntersectionObserver, onIntersect?: onIntersectFunction) => { 11 | el._intersectionObserver = observer 12 | el._onIntersect = onIntersect 13 | } 14 | 15 | function hasOwnProperty(obj: X, prop: Y): obj is X & Record { 16 | return Object.prototype.hasOwnProperty.call(obj, prop) 17 | } 18 | 19 | const extractOptions = (options: unknown) => { 20 | let observer: IntersectionObserver | undefined = undefined 21 | let onIntersect: onIntersectFunction | undefined = undefined 22 | if (options instanceof IntersectionObserver) { 23 | observer = options 24 | } else if (options && typeof options === 'object' && hasOwnProperty(options, 'observer') && options.observer instanceof IntersectionObserver) { 25 | observer = options.observer 26 | if (hasOwnProperty(options, 'onIntersect') && options.onIntersect instanceof Function) { 27 | onIntersect = options.onIntersect as onIntersectFunction 28 | } 29 | } 30 | return { observer, onIntersect } 31 | } 32 | 33 | export default { 34 | inserted(el: HTMLBaseElement, { value: options }: DirectiveBinding) { 35 | const { observer, onIntersect } = extractOptions(options) 36 | if (observer instanceof IntersectionObserver) { 37 | observer.observe(el) 38 | } 39 | setObserver(el, observer, onIntersect) 40 | }, 41 | update(el: HTMLBaseElementWithObserver, { value: newOptions }: DirectiveBinding) { 42 | const { observer: newObserver, onIntersect: newOnIntersect } = extractOptions(newOptions) 43 | const oldObserver = el._intersectionObserver 44 | const isOldObserver = oldObserver instanceof IntersectionObserver 45 | const isNewObserver = newObserver instanceof IntersectionObserver 46 | 47 | if (!isOldObserver && !isNewObserver) { 48 | return false 49 | } 50 | 51 | if (isOldObserver && isNewObserver && (oldObserver === newObserver)) { 52 | setObserver(el, newObserver, newOnIntersect) 53 | return false 54 | } 55 | 56 | if (oldObserver && isOldObserver) { 57 | oldObserver.unobserve(el) 58 | setObserver(el, undefined, undefined) 59 | } 60 | 61 | if (newObserver && isNewObserver) { 62 | newObserver.observe(el) 63 | setObserver(el, newObserver, newOnIntersect) 64 | } 65 | }, 66 | unbind(el: HTMLBaseElementWithObserver) { 67 | const cached = el._intersectionObserver 68 | if (cached instanceof IntersectionObserver) { 69 | cached.unobserve(el) 70 | } 71 | setObserver(el, undefined, undefined) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueDragscroll from 'vue-dragscroll' 3 | import App from '@/App.vue' 4 | import router from '@/router' 5 | import store from '@/store' 6 | import NodeIntersect from '@/directives/NodeIntersect' 7 | import '@/assets/main.sass' 8 | 9 | Vue.config.productionTip = false 10 | Vue.use(VueDragscroll) 11 | Vue.directive('NodeIntersect', NodeIntersect) 12 | 13 | new Vue({ 14 | router, 15 | store, 16 | render: h => h(App) 17 | }).$mount('#app') 18 | -------------------------------------------------------------------------------- /src/router/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import VueRouter from 'vue-router' 3 | import { routes } from './routes' 4 | 5 | Vue.use(VueRouter) 6 | 7 | const router = new VueRouter({ 8 | mode: 'hash', 9 | base: process.env.BASE_URL, 10 | routes 11 | }) 12 | 13 | export default router 14 | -------------------------------------------------------------------------------- /src/router/routes.js: -------------------------------------------------------------------------------- 1 | import Home from '@/views/Home.vue' 2 | import Examples from '@/views/Examples.vue' 3 | import Example1 from '@/views/Example1.vue' 4 | import Example2 from '@/views/Example2.vue' 5 | import Example3 from '@/views/Example3.vue' 6 | import Example4p1 from '@/views/Example4p1.vue' 7 | import Example4p2 from '@/views/Example4p2.vue' 8 | import Example4p3 from '@/views/Example4p3.vue' 9 | import Example5 from '@/views/Example5.vue' 10 | 11 | export const routes = [ 12 | { 13 | path: '/', 14 | name: 'home', 15 | component: Home 16 | }, 17 | { 18 | path: '/examples', 19 | name: 'examples', 20 | component: Examples, 21 | children: [ 22 | { 23 | path: '/example1', 24 | name: 'example1', 25 | component: Example1, 26 | meta: { 27 | title: 'Example 1. Object Watcher', 28 | description: ` 29 | Item watcher over object-like variable can produce redundant runs. 30 | Creating the separate primitive-type computed especially for the watcher solves the issue. 31 | `, 32 | instructions: ` 33 | Drag & drop items. 34 | There're 2 watchers: the first one over an itemIds object, the second one - over itemIdsTrigger string. 35 | Notice that both watchers run after drag & drop (console.log). 36 | Check any item. 37 | Notice that itemIds object watcher mistakenly detects the change during item check/uncheck while itemIdsTrigger string watcher runs only when it should. 38 | ` 39 | } 40 | }, 41 | { 42 | path: '/example2', 43 | name: 'example2', 44 | component: Example2, 45 | meta: { 46 | title: 'Example 2. Vuex + Object.freeze', 47 | description: ` 48 | Vuex makes each object property observable (recursively) by default. 49 | In some cases that is not needed, and it leads to high memory usage. 50 | One solution could be using Object.freeze before storing objects in vuex. 51 | `, 52 | instructions: ` 53 | Use chrome devtools memory tab. Add 100 items in a regular way. Take heap snapshot. 54 | Clear regular items, add 100 items using Object.freeze. Take another heap snapshot. 55 | Notice the difference. 56 | ` 57 | } 58 | }, 59 | { 60 | path: '/example3', 61 | name: 'example3', 62 | component: Example3, 63 | meta: { 64 | title: 'Example 3. Functional vs Map Getter', 65 | description: ` 66 | Functional getters are not cached. They are just plain functions and revaluated every time they are called. 67 | `, 68 | instructions: ` 69 | There's console.time invoked for itemById and itemByIds getters. 70 | Notice the first getter was called 10 times, the second one was called only once. 71 | ` 72 | } 73 | }, 74 | { 75 | path: '/example4p1', 76 | name: 'example4p1', 77 | component: Example4p1, 78 | meta: { 79 | title: 'Example 4.1. Incorrect Component Code Splitting', 80 | description: ` 81 | Incorrect component-code splitting causes every component rerendering when only one item changes. 82 | `, 83 | instructions: ` 84 | Add some items. Check an item, rename it or move. 85 | Notice that alongside with the target all the rest components trigger rerendering as well (use vue devtools performance component render tab). 86 | ` 87 | } 88 | }, 89 | { 90 | path: '/example4p2', 91 | name: 'example4p2', 92 | component: Example4p2, 93 | meta: { 94 | title: 'Example 4.2. Fixing Component Code Splitting - Stage 1', 95 | description: ` 96 | Renaming can be fixed by referring to the original itemsByIds instead of the getter. 97 | But it does not solve rerendering that happens after checking an item. 98 | `, 99 | instructions: ` 100 | Try to rename an item. It works correctly. 101 | Try to check an item. All the components mistakenly are rerendered. 102 | `, 103 | explanation: ` 104 | Renaming works correctly because here we refer to the original itemsByIds object. 105 | Renaming mutation does not update the entire object - it updates only particular item inside. 106 | From the other side, isChecked computed refers to the entire checkedIds array while trying to find if the item is checked. 107 | ` 108 | } 109 | }, 110 | { 111 | path: '/example4p3', 112 | name: 'example4p3', 113 | component: Example4p3, 114 | meta: { 115 | title: 'Example 4.3. Fixing Component Code Splitting - Stage 2', 116 | description: ` 117 | Rerendering can be fixed by providing exact related data by the parent component instead of searching the data from inside . 118 | `, 119 | instructions: ` 120 | Try to rename, check or move an item. It works correctly - only the target item gets updated. 121 | `, 122 | explanation: ` 123 | Here we provide the original item object and boolean isChecked prop by the parent list component. 124 | That granularity gives vue the possibility to detect if the has to be updated. 125 | ` 126 | } 127 | }, 128 | { 129 | path: '/example5', 130 | name: 'example5', 131 | component: Example5, 132 | meta: { 133 | title: 'Example 5. Intersection Observer', 134 | description: ` 135 | Sometimes the DOM is heavy by itself. 136 | This trick shows how IntersectionObserver can be used to skip DOM updates for the nodes outside of the viewport. 137 | `, 138 | instructions: ` 139 | Add some items. Each item toggles a heavy svg to blink every 500ms. Notice how lattency grows. 140 | Enable IntersectionObserver. It will hide svg-s outside of the viewport by using css display none. 141 | That helps performance a lot. 142 | ` 143 | } 144 | } 145 | ] 146 | } 147 | ] 148 | -------------------------------------------------------------------------------- /src/store/example1.js: -------------------------------------------------------------------------------- 1 | export const state = () => ({ 2 | items: [], 3 | checkedItemIds: [] 4 | }) 5 | 6 | export const getters = { 7 | extendedItems (state) { 8 | return state.items.map(item => ({ 9 | ...item, 10 | isChecked: state.checkedItemIds.includes(item.id) 11 | })) 12 | }, 13 | extendedItemsByIds (state, getters) { 14 | return getters.extendedItems.reduce((out, item) => { 15 | out[item.id] = item 16 | return out 17 | }, {}) 18 | } 19 | } 20 | 21 | export const mutations = { 22 | setItems (state, items) { 23 | state.items = items 24 | }, 25 | setCheckedItemIds (state, checkedItemIds) { 26 | state.checkedItemIds = checkedItemIds 27 | }, 28 | updateItemsOrder (state, { newIndex, oldIndex }) { 29 | state.items.splice(newIndex, 0, state.items.splice(oldIndex, 1)[0]) 30 | }, 31 | setCheckedItemById (state, { id, isChecked }) { 32 | const checkedItemIds = [...state.checkedItemIds] 33 | const index = checkedItemIds.indexOf(id) 34 | if (isChecked && index === -1) { 35 | checkedItemIds.push(id) 36 | } else if (!isChecked && index !== -1) { 37 | checkedItemIds.splice(index, 1) 38 | } 39 | state.checkedItemIds = checkedItemIds 40 | } 41 | } 42 | 43 | export const actions = { 44 | initializeItems ({ commit }, itemsCount = 5) { 45 | const items = [] 46 | for (let i = 0; i < itemsCount; i++) { 47 | items.push({ 48 | id: i + 1, 49 | title: `Item ${i + 1}` 50 | }) 51 | } 52 | commit('setItems', items) 53 | commit('setCheckedItemIds', []) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/store/example2.js: -------------------------------------------------------------------------------- 1 | export const state = () => ({ 2 | regularItems: [], 3 | frozenItems: [] 4 | }) 5 | 6 | export const mutations = { 7 | setRegularItems (state, items) { 8 | state.regularItems = items 9 | }, 10 | addRegularItems (state, items) { 11 | state.regularItems = [...state.regularItems, ...items] 12 | }, 13 | setFrozenItems (state, items) { 14 | state.frozenItems = items.map(Object.freeze) 15 | }, 16 | addFrozenItems (state, items) { 17 | state.frozenItems = [...state.frozenItems, ...items.map(Object.freeze)] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/store/example3.js: -------------------------------------------------------------------------------- 1 | export const state = () => ({ 2 | items: [] 3 | }) 4 | 5 | export const getters = { 6 | itemById: (state) => (itemId) => { 7 | console.count('itemById') 8 | return state.items.find(item => item.id === itemId) 9 | }, 10 | itemsByIds: (state) => { 11 | console.count('itemsByIds') 12 | return state.items.reduce((out, item) => { 13 | out[item.id] = item 14 | return out 15 | }, {}) 16 | } 17 | } 18 | 19 | export const mutations = { 20 | setItems (state, items) { 21 | state.items = items 22 | } 23 | } 24 | 25 | export const actions = { 26 | initializeItems ({ commit }, itemsCount = 10) { 27 | const items = [] 28 | for (let i = 0; i < itemsCount; i++) { 29 | items.push({ 30 | id: i + 1, 31 | title: `Item ${i + 1}` 32 | }) 33 | } 34 | commit('setItems', items) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/store/example4.js: -------------------------------------------------------------------------------- 1 | export const state = () => ({ 2 | ids: [], 3 | itemsByIds: {}, 4 | checkedIds: [] 5 | }) 6 | 7 | export const getters = { 8 | checkedIdsRev (state) { 9 | return state.checkedIds.reduce((out, id) => { 10 | out[id] = true 11 | return out 12 | }, {}) 13 | }, 14 | extendedItems (state, getters) { 15 | return state.ids.map(id => ({ 16 | ...state.itemsByIds[id], 17 | isChecked: !!getters.checkedIdsRev[id] 18 | })) 19 | }, 20 | extendedItemsByIds (_, getters) { 21 | return getters.extendedItems.reduce((out, extendedItem) => { 22 | out[extendedItem.id] = extendedItem 23 | return out 24 | }, {}) 25 | }, 26 | extendedItemsNested (state, getters) { 27 | return state.ids.map(id => ({ 28 | id, 29 | data: state.itemsByIds[id], 30 | isChecked: !!getters.checkedIdsRev[id] 31 | })) 32 | }, 33 | extendedItemsByIdsNested (_, getters) { 34 | return getters.extendedItemsNested.reduce((out, extendedItem) => { 35 | out[extendedItem.id] = extendedItem 36 | return out 37 | }, {}) 38 | } 39 | } 40 | 41 | export const mutations = { 42 | reset (state) { 43 | state.ids = [] 44 | state.itemsByIds = {} 45 | state.checkedIds = [] 46 | }, 47 | addItems (state, items) { 48 | const ids = [...state.ids] 49 | const itemsByIds = { ...state.itemsByIds } 50 | items.forEach((item) => { 51 | if (!ids.includes(item.id)) { 52 | ids.push(item.id) 53 | } 54 | itemsByIds[item.id] = Object.freeze(item) 55 | }) 56 | state.ids = ids 57 | state.itemsByIds = itemsByIds 58 | }, 59 | updateItemsOrder (state, { newIndex, oldIndex }) { 60 | state.ids.splice(newIndex, 0, state.ids.splice(oldIndex, 1)[0]) 61 | }, 62 | renameItem (state, { id, title }) { 63 | const item = state.itemsByIds[id] 64 | if (item) { 65 | state.itemsByIds[id] = Object.freeze({ 66 | ...item, 67 | title 68 | }) 69 | } 70 | }, 71 | setCheckedItemById (state, { id, isChecked }) { 72 | const index = state.checkedIds.indexOf(id) 73 | if (isChecked && index === -1) { 74 | state.checkedIds.push(id) 75 | } else if (!isChecked && index !== -1) { 76 | state.checkedIds.splice(index, 1) 77 | } 78 | }, 79 | deleteCheckedItems (state) { 80 | state.ids = state.ids.filter(id => !state.checkedIds.includes(id)) 81 | state.itemsByIds = state.ids.reduce((out, id) => { 82 | out[id] = state.itemsByIds[id] 83 | return out 84 | }, {}) 85 | state.checkedIds = [] 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/store/index.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Vuex from 'vuex' 3 | import * as example1 from './example1' 4 | import * as example2 from './example2' 5 | import * as example3 from './example3' 6 | import * as example4 from './example4' 7 | 8 | Vue.use(Vuex) 9 | 10 | export default new Vuex.Store({ 11 | modules: { 12 | example1: { ...example1, namespaced: true }, 13 | example2: { ...example2, namespaced: true }, 14 | example3: { ...example3, namespaced: true }, 15 | example4: { ...example4, namespaced: true } 16 | } 17 | }) 18 | -------------------------------------------------------------------------------- /src/views/Example1.vue: -------------------------------------------------------------------------------- 1 | 27 | 28 | 83 | -------------------------------------------------------------------------------- /src/views/Example2.vue: -------------------------------------------------------------------------------- 1 | 30 | 31 | 69 | -------------------------------------------------------------------------------- /src/views/Example3.vue: -------------------------------------------------------------------------------- 1 | 18 | 19 | 37 | -------------------------------------------------------------------------------- /src/views/Example4p1.vue: -------------------------------------------------------------------------------- 1 | 28 | 29 | 97 | -------------------------------------------------------------------------------- /src/views/Example4p2.vue: -------------------------------------------------------------------------------- 1 | 28 | 29 | 97 | -------------------------------------------------------------------------------- /src/views/Example4p3.vue: -------------------------------------------------------------------------------- 1 | 29 | 30 | 101 | -------------------------------------------------------------------------------- /src/views/Example5.vue: -------------------------------------------------------------------------------- 1 | 29 | 30 | 62 | -------------------------------------------------------------------------------- /src/views/Examples.vue: -------------------------------------------------------------------------------- 1 | 26 | -------------------------------------------------------------------------------- /src/views/Home.vue: -------------------------------------------------------------------------------- 1 | 18 | 19 | 34 | -------------------------------------------------------------------------------- /vue.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | publicPath: '/vue-rerendering-optimization/' 3 | } 4 | --------------------------------------------------------------------------------