Reputation: 61
The AMP documentation mentions using jQuery with the amp-script component: https://amp.dev/documentation/guides-and-tutorials/develop/custom-javascript/
However, I do not see any examples nor an explanation of how to do so.
I've tried including jQuery in the example AMP pages below (3.4.1 and 2.2.4 respectively), and running this simple jQuery script:
$('button').click(function() {
$('body').append('hello world');
})
Example AMP pages:
https://apps.yourstorewizards.com/sandbox/amp/amp-script/jquery3.html https://apps.yourstorewizards.com/sandbox/amp/amp-script/jquery2.html
Neither work as expected. Both produce javascript errors. Are there limitations as to which jQuery functions can be used in AMP?
Any help would be appreciated. Thanks.
Upvotes: 6
Views: 10102
Reputation: 151
If you look at the following example: https://github.com/ampproject/amphtml/blob/master/examples/amp-script/todomvc.amp.html
which uses Vue.js, you will see that in the example, the following script is referenced vue-todomvc.js,
<amp-script layout="container" src="/examples/amp-script/vue-todomvc.js" sandbox="allow-forms">
...
</amp-script>
In inspection of that file, you will notice that the vue.js library compressed is included at the top along with the custom javascript for the example.
So in the jquery case, the same would apply. You would include the jquery library in a custom file along with your custom javascript using jquery.
Ideally there should be a way to reference jquery library in the amp-script tag itself and have your custom JS inlined or referenced in a separate file for a better user experience. I am in the process of proposing such a change. Thanks
Example of how I would prefer for it to work.
<amp-script layout="container" src="https://code.jquery.com/jquery-1.11.3.js" sandbox="allow-forms">
... // custom js
</amp-script>
or
<amp-script layout="container" 3p-lib-src="https://code.jquery.com/jquery-1.11.3.js" sandbox="allow-forms" src="my-custom-js.js>
...
</amp-script>
Where there would be an attribute to reference the third party library, in this case 3p-lib-src and your custom js can reside in src.
Upvotes: 3