Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running JavaScript in AMP

Tags:

amp-html

I am a bit confused as to how JavaScript is suppposed to be run in an AMP page.

I got as far as understanding that my JavaScript must be executed in an iframe. Such iframe has to be placed down in the page (75% at least from top) and has to be served through https. This does indeed work:

<amp-iframe 
  width=300 
  height=300 
  sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox" 
  layout="responsive"
  frameborder="0" 
  src="https://localhost:8000/?p=myjs">
</amp-iframe>

In that page (https://localhost:8000/?p=myjs) I can freely run my js.

My problem is the following though:

How am I supposed to run my code against the document of the main page including the iframe?

I tried accessing window.parent.document and that is blocked. (of course).

Can anyone explain how AMP people think we can actually port pages to AMP if all our js gets killed? What is the recommended pattern to have our js run on an AMP page? Is there any such thing or is it just assumed that developers must dump all their code?

Thanks

like image 372
nourdine Avatar asked Oct 25 '16 10:10

nourdine


2 Answers

As of 11th of April 2019 Official Announcement,

Now you can include custom JavaScript in AMP pages

AMP pages support custom JavaScript through the <amp-script> component.

Try out amp-script example

<!doctype html>
<html ⚡>
<head>
  ...
  <script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>
<body>  
  ...
  <amp-script layout="container" src="https://example.com/myfile.js">
    <p>Initial content that can be modified from JavaScript</p>
  </amp-script>
  ...
</body>
</html>
like image 95
Divyesh Kanzariya Avatar answered Oct 19 '22 19:10

Divyesh Kanzariya


At the AMP Conf 2018 the support for custom JS in AMP using web workers was introduced. It should be ready later this year.

like image 35
niutech Avatar answered Oct 19 '22 19:10

niutech