Home > Blockchain >  How to load an external JavaScript on a condition
How to load an external JavaScript on a condition

Time:11-01

The question is how to rewrite a static HTML script embedding:

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

into a programmatic embedding which allows loading the script only on a certain condition.

The bounty is set for a description of how static/programmatic embedding differ from one another, specifically:

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

CodePudding user response:

If you've already figured out how to detect your criteria then loading another script goes like this:

<head>
<!-- the usual head stuff goes here -->
<script>
// replace `criteria` with your actual criteria
if(criteria) {
  const script = document.createElement('script');
  script.id = '__script__id__';
  script.type = 'text/javascript';
  script.async = true;
  script.src = '//abc.xyz.com/js/script.js';
  document.head.append(script);
}
</script>
<!-- remaining scripts go here -->
<!-- injected script will end up here -->
</head>

Check for the criteria, create the element, set its properties, add it to the document.


I took a shot at finding details on this mechanism. The best I could find was from MDN on the topic of script element async and defer properties:

The exact processing details for these attributes are complex, involving many different aspects of HTML, and therefore are scattered throughout the specification. These algorithms describe the core ideas, but they rely on the parsing rules for <script> start and end tags in HTML, in foreign content, and in XML; the rules for the document.write() method; the handling of scripting; and so on.

Unfortunately, I do not have the necessary familiarity with W3's various HTML specs to turn it into plain English and it looks like it would take quite a bit of time to become that familiar.

  • Related