For example, We have our folder structure of current theme:
We should focus four files:
Magento_Catalog/layout/catalog_product_view.xml Magento_Catalog/templates/product/js.phtml
- Add new template to call our jQuery plugin. That helps us to include our js on product detail page only.
Layout
#app/design/frontend/Boolfly/yume/Magento_Catalog/layout/catalog_product_view.xml
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template"
name="custom.js" as="custom.js" template="Magento_Catalog::product/js.phtml"/>
</referenceContainer>
</page>
Template:
#app/design/frontend/Boolfly/yume/Magento_Catalog/templates/product/js.phtml
<script>// <![CDATA[
require([
'jquery',
'hello'
], function ($) {
$('.product-info-main').HelloWorld();
});
// ]]>
</script>
app/design/frontend/Boolfly/yume/web/js/custom.js
We can create our own custom jQuery plugin.
define('jquery', function($) { $.fn.HelloWorld = function() { alert('Here'); } }(jQuery) );
app/design/frontend/Boolfly/yume/requirejs-config.js
Create a RequireJS configuration file.
var config = { map: { '*' : { 'hello' : 'js/custom' } } };
Clear Magento Cache and run static content deploy:
php bin/magento setup:static-content:deploy
php bin/magento cache:clean
We can read more here how to create custom Javascript: http://devdocs.magento.com/guides/v2.0/javascript-dev-guide/javascript/custom_js.html