Search code examples
javascriptloadingamp-htmlaccelerated-mobile-page

AMP Load only the necessary scripts


I have a template file for my AMP pages in which I am loading several amp functionalities:

<script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>
<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>
<script async custom-element="amp-twitter" src="https://cdn.ampproject.org/v0/amp-twitter-0.1.js"></script>

What I would like to do is only load the necessary scripts. While I was browsing the web I've found that this is a requested feature but it has not been yet implemented: https://github.com/ampproject/amphtml/issues/9712

My idea is to check if a certain tag is present in the body of the document and if it is, load the script. For example:

document.addEventListener("DOMContentLoaded", function(event) {
        var list = document.getElementsByTagName("amp-youtube");
        //if list is not empty, create a script tag having the corresponding 
        //src and append it to the body
    });

However, this will add the tag at the end of the body and I don't know if that is okay (everywhere where I looked on the web the script tags were loaded in the header). I'm a beginner to AMP pages so my question is: would this be a good approach to solve my problem and if not, how can I implement the desired functionality?


Solution

  • If I understand you question correctly, what you want is to allow your page to load different set of scripts on different routes. And you're right currently there's no way to do this AFAIK.

    How I do this is by using a templating engine ( React on server side or pug which I'm using ). Now you can have route based headers by using the respective template systems.

    Hope this helps! Do revert back if this does not answer you question.