• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

How to Improve Performance of FluentUI People Picker with Photos?

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Introduction to Improving Performance in People Picker


When working with a FluentUI People Picker that retrieves user photos from the Microsoft Graph API, you may notice significant performance issues. Specifically, fetching user photos can slow down response times dramatically compared to retrieving just user data. This article addresses how to improve performance while still incorporating user photos in a People Picker.

Understanding the Performance Issue


The primary reason for performance degradation when fetching user photos lies in the asynchronous nature of HTTP requests. Each user photo involves a separate API call, which can quickly accumulate and result in slow response times, especially if there are many users to process.

The initial API call to fetch users is efficient; however, each subsequent call to retrieve user photos can create latency in your application, leading to a poor user experience. Therefore, it's crucial to optimize these requests for a smoother experience.

Optimizing User Photo Fetching


Here are several strategies to improve the performance of your People Picker while still fetching user photos:

1. Batching API Requests


Instead of fetching each user's photo in its own request, consider utilizing the Graph API's batching feature. Batching allows you to group multiple requests into a single HTTP call. Here's how to implement it:

Example of Batching Requests in TypeScript


public async getPeoplePickerPhotos(userIds: string[]): Promise<{[key: string]: string | null}> {
const batchRequests = userIds.map(id => ({
id: id,
method: 'GET',
url: `/users/${id}/photo/$value`
}));

const batchResponse = await this.httpClient.post('/$batch', {
requests: batchRequests
});

const photos: {[key: string]: string | null} = {};
batchResponse.data.responses.forEach(response => {
if (response.status === 200) {
photos[response.id] = URL.createObjectURL(response.body);
} else {
photos[response.id] = null;
}
});

return photos;
}

2. Using Placeholders


While fetching user photos, consider displaying a placeholder image for users whose photos are not yet loaded. This approach keeps the application responsive while the photos are being fetched in the background. Update your original People Picker to include a placeholder:

const usersWithPhotos = await this.getPeoplePickerPhotos(users.map(user => user.id));

return users.map((user, index) => ({
key: index,
text: user.displayName,
secondaryText: user.mail,
id: user.id,
imageUrl: usersWithPhotos[user.id] || '/path/to/placeholder/image.png',
}));

3. Lazy Loading Photos


Instead of loading all user photos at once, consider lazy loading. This means you only load photos as they are needed (e.g., as users scroll through the list). You can implement lazy loading by triggering the photo fetch when a user selects a specific person:

Example of Lazy Loading User Photos


async onUserSelect(userId: string) {
// Check if the photo is already fetched
if (!this.userPhotos[userId]) {
const photoUrl = await this.fetchUserPhoto(userId);
this.userPhotos[userId] = photoUrl;
}
this.selectedUser = this.userPhotos[userId];
}

Conclusion


By implementing these optimizations—batching API requests, using placeholders, and lazy loading photos—you can significantly improve the performance of your FluentUI People Picker while still providing a visually appealing and functional interface. This approach not only enhances user experience but also adheres to best practices in modern web development.

Frequently Asked Questions (FAQ)

1. What is the benefit of using batch requests?


Batch requests reduce the number of HTTP calls made, thus improving the overall performance of data retrieval.

2. How can placeholders improve user experience?


Placeholders provide immediate visual feedback to users, indicating that data is being loaded, which can improve perceived performance.

3. Does lazy loading affect user experience?


Yes, lazy loading can enhance user experience by preventing the application from lagging and loading data only as needed.

By combining these strategies, you can create a more efficient tool without sacrificing the richness of user data in your application.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу