У попередніх статтях ми розглянули основи створення нашої бібліотеки ModernDOM та налаштували процес розробки. Сьогодні ми зосередимося на додаванні розширеної функціональності та оптимізації продуктивності нашої бібліотеки.
1. Додавання AJAX-функціональності
Почнемо з додавання базової AJAX-функціональності. Створимо новий файл src/modules/ajax.js:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
$.ajax = function(options) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open(options.method || 'GET', options.url); if (options.headers) { Object.keys(options.headers).forEach(key => { xhr.setRequestHeader(key, options.headers[key]); }); } xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.response); } else { reject(xhr.statusText); } }; xhr.onerror = () => reject(xhr.statusText); xhr.send(options.data); }); }; $.get = function(url, data) { return $.ajax({url: url, data: data, method: 'GET'}); }; $.post = function(url, data) { return $.ajax({url: url, data: data, method: 'POST'}); }; |
2. Додавання анімацій
Створимо простий модуль для анімацій. Додамо файл src/modules/animations.js:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
$.prototype.fadeIn = function(duration = 400) { this.forEach(elem => { elem.style.opacity = 0; elem.style.display = ''; let start = null; function step(timestamp) { if (!start) start = timestamp; const progress = timestamp - start; elem.style.opacity = Math.min(progress / duration, 1); if (progress < duration) { window.requestAnimationFrame(step); } } window.requestAnimationFrame(step); }); return this; }; $.prototype.fadeOut = function(duration = 400) { this.forEach(elem => { let start = null; function step(timestamp) { if (!start) start = timestamp; const progress = timestamp - start; elem.style.opacity = 1 - Math.min(progress / duration, 1); if (progress < duration) { window.requestAnimationFrame(step); } else { elem.style.display = 'none'; } } window.requestAnimationFrame(step); }); return this; }; |
3. Оптимізація продуктивності
Для оптимізації продуктивності нашої бібліотеки, додамо кешування та використаємо техніку делегування подій. Оновимо src/core.js:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
const $ = function(selector) { if (typeof selector === 'function') { document.addEventListener('DOMContentLoaded', selector); return; } return new $.prototype.init(selector); }; // Кешування селекторів const selectorCache = {}; $.prototype.init = function(selector) { if (!selector) { return this; } if (selector.tagName) { this[0] = selector; this.length = 1; return this; } if (selectorCache[selector]) { return selectorCache[selector]; } Object.assign(this, document.querySelectorAll(selector)); this.length = document.querySelectorAll(selector).length; selectorCache[selector] = this; return this; }; // Делегування подій $.on = function(eventName, selector, handler) { document.addEventListener(eventName, function(event) { const targets = document.querySelectorAll(selector); if (targets) { const target = event.target.closest(selector); if (target && Array.from(targets).includes(target)) { handler.call(target, event); } } }); }; |
4. Робота з формами
Додамо функціональність для роботи з формами. Створимо файл src/modules/forms.js:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$.prototype.serializeArray = function() { if (this[0].tagName.toLowerCase() !== 'form') return []; return Array.from(new FormData(this[0])).map(([name, value]) => ({name, value})); }; $.prototype.serialize = function() { return this.serializeArray().map(item => `${encodeURIComponent(item.name)}=${encodeURIComponent(item.value)}`).join('&'); }; $.prototype.val = function(value) { if (typeof value === 'undefined') { return this[0].value; } this.forEach(elem => elem.value = value); return this; }; |
5. Підтримка ланцюжків методів
Переконаємося, що всі наші методи підтримують ланцюжки. Додамо в кінець кожного методу return this;, якщо це ще не зроблено.
Висновок
У цій статті ми значно розширили функціональність нашої бібліотеки ModernDOM, додавши підтримку AJAX, анімацій та роботи з формами. Ми також оптимізували продуктивність за допомогою кешування та делегування подій.
Наша бібліотека тепер пропонує широкий спектр можливостей, залишаючись при цьому легкою та ефективною. Вона може бути хорошою альтернативою для проектів, які не потребують повноцінного фреймворку, але вимагають більше, ніж просто ванільний JavaScript.
У наступній статті ми розглянемо тестування нашої бібліотеки, створення документації та стратегії для забезпечення кросбраузерної сумісності.