About
Third Party Scripts are scripts that have been created by a third party.
Example:
- Google Adsense
- Google Analytics
- Twitter
- …
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
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
- Given this HTTP - Content security policy (CSP) header
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>
Documentation / Reference
- Best practices for using third-party embeds - https://web.dev/embed-best-practices/