How to use jQuery with amp-script?

两盒软妹~` 提交于 2020-02-28 15:45:02

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/57828607/how-to-use-jquery-with-amp-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!