Tuesday 26 October 2021

How to load external JavaScript on a condition

There is a script on the page being loaded asynchronously:

<script async id="__script__id__" type="text/javascript" src="//abc.xyz.com/js/script.js"></script>

There is a 100% certainty that the script is only used on desktop versions of the site. How do I rewrite the code to load the script only for desktops (by screen width) and not on mobiles?

Update. Question is about how to make a programmatic JavaScript equivalent of the HTML code above which does the same job.

P.S. I used search and found an answer to a similar question dated the year 2015. I am sure there might have been some changes and the question seems important.

Bounty.

  1. Explain how JS specification treats programmatically added scripts — when they are loaded and executed — with authoritative references.
  2. Explain how converting script loading from HTML inline to programmatic affects browser optimizations (it's known that browser scans for HTML script tags with src and preloads them) with authoritative references.


from How to load external JavaScript on a condition

No comments:

Post a Comment