Skip to content

Instantly share code, notes, and snippets.

@nleush
Last active February 10, 2020 20:44
Show Gist options
  • Save nleush/4cae990f0cdfd2008a6b8fe05e7b9d2d to your computer and use it in GitHub Desktop.
Save nleush/4cae990f0cdfd2008a6b8fe05e7b9d2d to your computer and use it in GitHub Desktop.
Iframely get amp script
var AMP_COMPONENTS_ON_DEMAND = {
"apester-media": "v0/amp-apester-media-0.1.js",
"brightcove": "v0/amp-brightcove-0.1.js",
"dailymotion": "v0/amp-dailymotion-0.1.js",
"facebook-page": "v0/amp-facebook-page-0.1.js",
"facebook": "v0/amp-facebook-0.1.js",
"gfycat": "v0/amp-gfycat-0.1.js",
"gist": "v0/amp-gist-0.1.js",
"iframe": "v0/amp-iframe-0.1.js",
"iframely": "v0/amp-iframely-0.1.js",
"instagram": "v0/amp-instagram-0.1.js",
"soundcloud": "v0/amp-soundcloud-0.1.js",
"twitter": "v0/amp-twitter-0.1.js",
"vimeo": "v0/amp-vimeo-0.1.js",
"wistia-player": "v0/amp-wistia-player-0.1.js",
"youtube": "v0/amp-youtube-0.1.js",
};
function extractAMPComponentsName(html) {
var matches = html && html.match && html.match(/(?<=\<amp-)[\w-]+/g);
return matches || [];
}
function generateAMPScriptTagsByNames(componentsList) {
var componentsInUse = {};
var scriptsToBeAdded = [];
componentsList.forEach(function(component) {
if (component && !(component in componentsInUse)) {
componentsInUse[component] = true;
if (component in AMP_COMPONENTS_ON_DEMAND) {
// Amp script from whitelist.
scriptsToBeAdded.push('<script async custom-element="amp-' + component + '" src="https://cdn.ampproject.org/' + AMP_COMPONENTS_ON_DEMAND[component] + '"></script>');
}
}
});
return scriptsToBeAdded.join('\n');
}
function generateAMPScriptTags(html) {
var componentsList = extractAMPComponentsName(html);
return generateAMPScriptTagsByNames(componentsList);
}
// Usage example:
var articleHTML = '…. prepared article code with <amp-…> elements in it';
var orSingleEmbedCode = '<amp-…>…</amp-…>';
var head = '<head>';
head += generateAMPScriptTags(articleHTML);
head += generateAMPScriptTags(orSingleEmbedCode);
/*
Outputs required <scripts> a la
<script async custom-element="amp-apester-media" src="https://cdn.ampproject.org/v0/amp-apester-media-0.1.js"></script>
<script async custom-element="amp-brightcove" src="https://cdn.ampproject.org/v0/amp-brightcove-0.1.js"></script>"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment