HTML - Third Party Script

> (World Wide) Web - (W3|WWW) > HyperText markup Language (HTML)

1 - About

Third Party Script are script that have been created by third party.

Example:

  • Google adsense
  • Google Analytics
Advertising

3 - Management

3.1 - Loading

3.1.1 - Browser

Third party script

Example loading asynchronously Facebook library

(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'));

3.1.2 - Node

loadScript.js
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.');
      },
    );

3.2 - Security

Content-Security-Policy: script-src https://example.com/
  • The following third-party script will not be loaded or executed
<script src="https://not-example.com/js/library.js"></script>
Advertising