0

The issue is that we need to replace some HTML based on the user's user agent string but by the time the JS code is loaded and runs, the user is already interacting with the page.

Is there some way to ensure wp_enqueue_script will enqueue a script as early as possible? We're already enqueuing without any dependency array, but users are often able to interact with the page before a simple replacement of a URL is done (done based on the Browser user agent string.)

Or is there some way we could do said replacement server-side to circumvent this?

For example we might have a link like https://example.org/download-for-windows by default and we need to replace it with https://example.org/download-for-linux when a Linux user-agent is detected.

4
  • Are you enqueueing the script in the header or footer? If you're not sure check the documentation for wp_enqueue_script. Jul 28, 2022 at 6:17
  • 1
    Most general JavaScript targeting the DOM is written to execute after the DOM has finished loading - as would be required here in order to target all available links (outside of introducing a large amount of complexity). So you could load your script as early as possible, but it would likely still have to wait for the DOM. It sounds to me like you should consider performing the substitution in PHP instead
    – bosco
    Jul 28, 2022 at 18:01
  • @bosco can you help me understand; when performing the substitution in PHP, how would that interact with full-page caching? E.g. Nginx caching? I'd think it would break full page caching, or show the same output for users regardless of user-agent. Any idea?
    – Slbox
    Jul 28, 2022 at 21:33
  • 1
    Ah you are correct - caching does complicate things! Those portions would indeed to circumvent caching. If there are just a few versions though it would be possible to cache each separately, but probably require some custom code or server configuration to select which to serve. Or sticking to JS, perhaps you could delay/disable/grey-out/loading-spinner the display of the links until after you've managed to make the substitution?
    – bosco
    Jul 28, 2022 at 21:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy