Speculative Loading

Descrição

This plugin adds support for the Speculation Rules API, which allows defining rules by which certain URLs are dynamically prefetched or prerendered.

See the Speculation Rules WICG specification draft.

By default, the plugin is configured to prerender WordPress frontend URLs when the user interacts with a relevant link. This can be customized via the “Speculative Loading” section in the Settings > Reading admin screen.

A filter can be used to exclude certain URL paths from being eligible for prefetching and prerendering (see FAQ section). Alternatively, you can add the no-prerender CSS class to any link (<a> tag) that should not be prerendered. See FAQ for more information.

Suporte dos navegadores

The Speculation Rules API is a new web API, and the functionality used by the plugin is supported in Chromium-based browsers such as Chrome, Edge, or Opera using version 121 or above. Other browsers such as Safari and Firefox will ignore the functionality with no ill effects; they will simply not benefit from the speculative loading. Note that certain browser extensions may disable preloading by default.

Este plugin era anteriormente conhecido como Speculation Rules.

Instalação

Instalação a partir do WordPress

  1. Visite o menu Plugins > Adicionar novo.
  2. Pesquise por Speculative Loading.
  3. Instale e active o plugin Speculative Loading.

Instalação manual

  1. Upload the entire speculation-rules folder to the /wp-content/plugins/ directory.
  2. Visite plugins.
  3. Active o plugin Speculative Loading.

Perguntas frequentes

How can I prevent certain URLs from being prefetched and prerendered?

Not every URL can be reasonably prerendered. Prerendering static content is typically reliable, however prerendering interactive content, such as a logout URL, can lead to issues. For this reason, certain WordPress core URLs such as /wp-login.php and /wp-admin/* are excluded from prefetching and prerendering. Additionally, any URLs generated with wp_nonce_url() (or which contains the _wpnonce query var) and nofollow links are also ignored. You can exclude additional URL patterns by using the plsr_speculation_rules_href_exclude_paths filter.

The following example ensures that URLs like https://example.com/cart/ or https://example.com/cart/foo are excluded from prefetching and prerendering:

<?php
add_filter(
    'plsr_speculation_rules_href_exclude_paths',
    function ( array $exclude_paths ): array {
        $exclude_paths[] = '/cart/*';
        return $exclude_paths;
    }
);

Lembre-se de que, às vezes, pode ser útil excluir um URL da pré-renderização e, ao mesmo tempo, permitir que ele seja pré-obtido. Por exemplo, uma página com JavaScript do lado do cliente para actualizar o estado do utilizador provavelmente não deve ser pré-renderizada, mas seria razoável fazer a pré-obtenção.

Para este efeito, o filtro plsr_speculation_rules_href_exclude_paths recebe o modo actual (ou “prefetch” ou “prerender”) para fornecer exclusões condicionais.

The following example ensures that URLs like https://example.com/products/... cannot be prerendered, while still allowing them to be prefetched:

<?php
add_filter(
    'plsr_speculation_rules_href_exclude_paths',
    function ( array $exclude_paths, string $mode ): array {
        if ( 'prerender' === $mode ) {
            $exclude_paths[] = '/products/*';
        }
        return $exclude_paths;
    },
    10,
    2
);

As mentioned above, adding the no-prerender CSS class to a link will prevent it from being prerendered (but not prefetched). Additionally, links with rel=nofollow will neither be prefetched nor prerendered because some plugins add this to non-idempotent links (e.g. add to cart); such links ideally should rather be buttons which trigger a POST request or at least they should use wp_nonce_url().

Are there any special considerations for speculative loading behavior?

For safety reasons, the entire speculative loading feature is disabled by default for logged-in users and for sites that do not use pretty permalinks. The latter is the case because plugins often use URLs with custom query parameters to let users perform actions, and such URLs should not be speculatively loaded. For sites without pretty permalinks, it is impossible or at least extremely complex to differentiate between which query parameters are Core defaults and which query parameters are custom.

If you are running this plugin on a site without pretty permalinks and are confident that there are no custom query parameters in use that can cause state changes, you can opt in to enabling speculative loading via the plsr_enabled_without_pretty_permalinks filter:

<?php
add_filter( 'plsr_enabled_without_pretty_permalinks', '__return_true' );

How will this impact analytics and personalization?

Prerendering can affect analytics and personalization.

For client-side JavaScript, is recommended to delay these until the prerender is activated (for example by clicking on the link). Some solutions (like Google Analytics) already do this automatically, see Impact on Analytics. Additionally, cross-origin iframes are not loaded until activation which can further avoid issues here.

Speculating with the default moderate eagerness decreases the risk that the prerendered page will not be visited by the user and therefore will avoid any side effects of loading such a link in advance. In contrast, eager speculation increases the risk that prerendered pages may not be loaded. Alternatively, the plugin offers to only speculate on mouse/pointer down (conservative) which reduces the risk even further and is an option for sites which are concerned about this, at the cost of having less of a lead time and so less of a performance gain.

A prerendered page is linked to the page that prerenders it, so personalisation may already be known by this point and changes (e.g. browsing other products, or logging in/out) often require a new page load, and hence a new prerender, which will then take these into account. But it definitely is something to be aware of and test! Prerendered pages can be canceled by removing the speculation rules <script> element from the page using standard JavaScript DOM APIs should this be needed when state changes without a new page load.

Onde posso submeter os meus comentários sobre o plugin?

Os comentários são incentivados e muito apreciados, especialmente porque este plugin pode conter futuros recursos principais do WordPress. Se tiver sugestões ou pedidos de novas funcionalidades, pode submetê-las como um problema no repositório GitHub da equipa de Performance do WordPress. Se precisar de ajuda com a solução de problemas ou tiver uma pergunta sobre o plugin, crie um novo tópico no nosso fórum de suporte.

Onde posso comunicar erros de segurança?

A equipa de Performance e a comunidade WordPress levam os bugs de segurança a sério. Apreciamos os seus esforços para divulgar de forma responsável as suas descobertas e faremos todos os esforços para reconhecer as suas contribuições.

Para comunicar um problema de segurança, visite o programa WordPress HackerOne.

Como posso contribuir para o desenvolvimento do plugin?

As contribuições são sempre bem-vindas! Saiba mais sobre como participar no manual da equipa de Core Performance.

Avaliações

19 Julho, 2024 1 resposta
I was using another plugin which does a similar job but Speculative Loading appears to be substantially quicker. Using on about 10 sites and no issues. Thank you
27 Maio, 2024
Es verkürzt die Ladzeit für einen Benutzer sichtbar, auch wenn im Hintergrund die Seite gleichschnell geladen wird, so fühlt es sich für einen Benutzer extrem schnell an.
8 Maio, 2024 1 resposta
I’ve currently activated this plugin on five sites, some on one server, and then others on another. The plugin has yet to present any plugin conflicts or other issues. The time to load pages is drastically improved based on user intent, and based on this alone, I cannot recommend this plugin enough. I haven’t tested the sites with Lighthouse, but honestly, I don’t feel the need to do that, because it’s about the user experience first, and that is such an improvement with this plugin. Thank you!
Ler todas as 17 avaliações

Contribuidores e programadores

“Speculative Loading” é software de código aberto. As seguintes pessoas contribuíram para este plugin:

Contribuidores

“Speculative Loading” foi traduzido para 10 locales. Obrigado aos tradutores pelas suas contribuições.

Traduza o “Speculative Loading” para o seu idioma.

Interessado no desenvolvimento?

Consulte o código, consulte o repositório SVN, ou subscreva o registo de alterações por RSS.

Registo de alterações

1.5.0

Enhancements

  • Add support for Speculative Loading WP Core API, loading the plugin’s own API implementation conditionally. (1883)

1.4.0

Enhancements

  • Implement speculative loading considerations for safer behavior. (1784)

1.3.1

Correcções de erros

  • Check if rel contains nofollow instead of being just nofollow when excluding speculative loading. (1232)

1.3.0

Enhancements

  • Prevent speculatively loading links to the uploads, content, plugins, template, or stylesheet directories. (1167)
  • Facilitate embedding Speculative Loading in other plugins/themes. (1159)
  • Improve overall code quality with stricter static analysis checks. (775)
  • Bump minimum PHP requirement to 7.2. (1130)

1.2.2

Correcções de erros

  • Fix composition of href exclude paths to account for JSON encoding and differing site/home URLs. (1164)

Documentação

  • Update readme with browser support and FAQ section about analytics and personalization. (1155)

1.2.1

Enhancements

  • Add settings link to Speculative Loading plugin action links. (1145)
  • Bump minimum PHP version to 7.2. (1130)

Correcções de erros

  • Exclude _wpnonce URLs in speculation rules. (1143)
  • Exclude rel=nofollow links from prefetch/prerender. (1142)

1.2.0

  • Add missing uninstall.php to remove plugin’s database option. (1128)

1.1.0

  • Allow excluding URL patterns from prerendering or prefetching specifically. (1025)
  • Rename plugin to “Speculative Loading”. (1101)
  • Add Speculative Loading generator tag. (1102)
  • Bump minimum required WP version to 6.4. (1062)
  • Update tested WordPress version to 6.5. (1027)

1.0.1

  • Escape path prefix and restrict it to be a pathname in Speculation Rules. (951)
  • Force HTML5 script theme support when printing JSON script. (952)
  • Add icon and banner assets for plugin directory. (987)

1.0.0

  • Initial release of the Speculative Loading plugin as a standalone plugin. (733)