Magento – Magento 2: Adding external CSS and JS to only one content page, and use jquery functions inside the content

javascriptjquerymagento2requirejs

I am trying to add some dynamic function to one content page of a Magento 2 site, but didn't manage to do it. Here is what I thought:

1) Adding the external javascript files at the "Layout Update XML" under "design":

<head>
<css src="https://xxxxxx.com/xxxx/css/abc.css" src_type="url" />
<script src="https://xxxxxx.com/xxxx/js/abc.js" src_type="url" />
</head>

2) at the "content" of the page:

<p>some contents</p>
<script type="text/javascript">
require(['jquery'], function ($) {
//my functions here xxyy
});
</script>

However, it didn't work. The console shows "jQuery" is not defined, and the xxyy is not a function.

I don't intend to add these JS files and CSS files globally, as I will only use this function at this content page only. What am I missing here?

Your help is much appreciated!

Best Answer

Have a look at this thread: How to use jquery library in Magento 2?

As Shaheer Ali points out on that page:

If you are adding your custom js library other the jQuery then you need to include the js code inside require function like:

require(['jquery', 'jquery/ui'], function($){ //your js code here });