Determinar se uma página foi carregada inicialmente em segundo plano (por exemplo, aberta em uma nova guia em segundo plano) é fundamental para um monitoramento de desempenho preciso. As páginas carregadas em segundo plano geralmente têm renderização atrasada e tempos de métrica mais longos (como First Contentful Paint). Ao identificar essas páginas, você pode filtrá-las da análise de performance para evitar dados distorcidos.
A maneira mais precisa de medir isso é usando a API VisibilityStateEntry, que registra de forma confiável as mudanças de visibilidade na linha do tempo de desempenho do navegador, independentemente de quando o script é executado.
Como detectar a visibilidade inicial e o tempo em segundo plano
OBRIGATÓRIO: use performance.getEntriesByType('visibility-state') para acessar o histórico de visibilidade exato. Não confie apenas na verificação de document.visibilityState no momento da execução, porque ela está sujeita a disputas.
/**
* Accurately determines visibility state history using the Performance API.
*/
function getVisibilityInfo() {
// Retrieve VisibilityStateEntry members:
const entries = performance.getEntriesByType('visibility-state');
if (entries.length > 0) {
const firstEntry = entries[0];
// If the first performance entry for visibility is 'hidden',
// the page was loaded in the background.
const initiallyBackgrounded = firstEntry.name === 'hidden';
// Find the precise, high-resolution timestamp of when the page
// was first backgrounded.
let timeBackgrounded = null;
for (const entry of entries) {
if (entry.name === 'hidden') {
// entry.startTime is used because it provides the exact browser
// timestamp of the visibility change, which is required for precision
timeBackgrounded = entry.startTime;
break;
}
}
return {
initiallyBackgrounded,
timeBackgrounded
};
}
}
Estratégias de fallback
Em ambientes sem suporte, você pode verificar a propriedade document.visibilityState ou detectar o evento visibilitychange.
OBRIGATÓRIO: é preciso entender que essa abordagem de fallback geralmente é muito imprecisa para determinar o estado inicial em segundo plano. Como os scripts podem ser carregados e executados de forma assíncrona, uma página pode ser aberta em uma guia em segundo plano e, em seguida, colocada em primeiro plano pelo usuário antes que o script termine de ser baixado e executado. Quando o script finalmente for executado, document.visibilityState será lido de forma síncrona como 'visible', e você vai presumir incorretamente que a página foi carregada em primeiro plano, perdendo completamente o estado oculto inicial. Além disso, o carimbo de data/hora substituto não tem a precisão interna da API Performance. Se a precisão for uma prioridade alta, não use o substituto.
/**
* Fallback implementation using document.visibilityState.
* This approach is prone to race conditions if the script loads asynchronously.
*/
function getFallbackVisibilityInfo() {
// Check the state exactly when this script executes.
// This will fail to detect an initial background state if the user
// foregrounded the page before this script executed.
let initiallyBackgrounded = document.visibilityState === 'hidden';
// If it's hidden now, we approximate that it was hidden from load (time 0).
let timeBackgrounded = initiallyBackgrounded ? 0 : null;
// Listen for future visibility changes to capture if it is backgrounded later.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden' && timeBackgrounded === null) {
// performance.now() is used here as a fallback, but it only gives
// us the time the event listener fired, not the precise internal
// browser time the visibility actually changed.
timeBackgrounded = performance.now();
}
});
return {
get initiallyBackgrounded() { return initiallyBackgrounded; },
get timeBackgrounded() { return timeBackgrounded; }
};
}
// Modern implementation using VisibilityStateEntry API.
function getVisibilityInfo() {
// Code omitted here would be the same modern
// implementation shown earlier in this guide
// ...
}
// DO: Detect if the VisibilityStateEntry API is available
if ('VisibilityStateEntry' in window) {
// DO: If VisibilityStateEntry is available, use it first:
getVisibilityInfo();
} else {
// DO: If VisibilityStateEntry is unavailable, fall back to `document.visibilityState`:
getFallbackVisibilityInfo();
}