title: Load script file on demand with vanilla js
body: <p>I use an accordion or tabs. When clicking on a tab, I want to display a map or something that require a big javascript file to load.</p>
  <p>To not load the big javascript when it is not needed, I want to load it only when the tab is clicked.</p>
  <p>How can I do that? I've created a good starting point with accordion and a click event.</p>
  <ul>
  <li>I use vanilla js (pure javascript - no jQuery)</li>
  <li>I use it on a webpage (not nodejs)</li>
  <li>I'm fine if it works with modern browsers (IE not needed)</li>
  </ul>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>window.addEventListener('DOMContentLoaded', () =&gt; {
    document.querySelector('[data-trigger]').addEventListener('click', () =&gt; {
      console.log('Load script from file');
      // CDN example - https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/1.12.0/mapbox-gl.js
    });
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
    list-style: none;
    margin: 0;
    padding: 0;
  }
  
  label {
    display: flex;
    align-items: center;
  }
  
  label:before {
    content: '';
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' d='M0 0h24v24H0z'/%3E%3Cpath d='M13.172 12l-4.95-4.95 1.414-1.414L16 12l-6.364 6.364-1.414-1.414z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    width: 24px;
    height: 24px;
  }
  
  input[type=checkbox] {
    display: none;
  }
  
  input[type=checkbox]:checked ~ h2 label:before {
    transform: rotate(90deg);
  }
  
  p {
    display: none;
  }
  
  input[type=checkbox]:checked ~ h2 ~ p {
    display: block;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt;
    &lt;li&gt;
      &lt;input type="checkbox" id="faq-1"&gt;
      &lt;h2 data-trigger&gt;
        &lt;label for="faq-1"&gt;Click to load map&lt;/label&gt;
      &lt;/h2&gt;
      &lt;p&gt;Gummies marzipan croissant chupa chups.&lt;/p&gt;
    &lt;/li&gt;
  
    &lt;li&gt;
      &lt;input type="checkbox" id="faq-2"&gt;
      &lt;h2&gt;
        &lt;label for="faq-2"&gt;Something else&lt;/label&gt;
      &lt;/h2&gt;
      &lt;p&gt;Cookie bear claw carrot cake croissant.&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ul&gt;</code></pre>
  </div>
  </div>
  </p>