Table of Contents

HTML - Third Party Script

About

Third Party Scripts are scripts that have been created by a third party.

Example:

Third-party embeds are typically loaded in <iframe> elements on the page. Third-party providers offer HTML snippets often consisting of an <iframe> that pulls in a page composed of markup, scripts, and stylesheets. Some providers also use a script snippet that dynamically injects an <iframe> to pull other content in.

Management

Loading

Browser

Third party script

Example loading asynchronously Facebook library. More How to load a script dynamically with Javascript?

(function (d, s, id) {
    var js;
    // Get the first script element
    var fjs = d.getElementsByTagName(s)[0];
    // if the element already exist with the id. do nothing
    if (d.getElementById(id)) {
        return;
    }
    // Create a script element
    js = d.createElement(s);
    js.id = id;
    js.src = "//connect.facebook.net/en_US/all.js";
    // get the parent node (the head normally) and insert it before the first one
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

Node

export default url =>
  new Promise((resolve, reject) =>
    document.head.appendChild(
      Object.assign(document.createElement('script'), {
        async: true,
        src: url,
        onload: resolve,
        onerror: reject,
      }),
    ),
  );

Usage:

import loadScript from './loadScript';

const url = 'https://...';
loadScript(url).then(
      () => {
         loaded = true;
      },
      error => {
        console.error('Failed to load.');
      },
    );

Security

Content-Security-Policy: script-src https://example.com/

<script src="https://not-example.com/js/library.js"></script>

Documentation / Reference