How add js and css on home page (slider) to Magento 2?

Add css and js from your frontend layout file

You need to add below code in app/code/Vendor/Modulename/frontend/layout/routname_controllername_action.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="Vendor_Modulename::js/your-js.js"/>
        <css src="Vendor_Modulename::css/your-css.css"/>
    </head>
    <body>
    </body>
</page>

Your js and css path will be

app/code/Vendor/Modulename/frontend/web/css/your-css.css app/code/Vendor/Modulename/frontend/web/js/your-js.js


This is correct way!

  1. Path: app/design/frontend/My-vendor/my-name-theme/web
  2. Add masterslider.min.js to app/design/frontend/My-vendor/my-name-theme/web/js
  3. Create requirejs-config.js to app/design/frontend/My-vendor/my-name-theme

    var config = { paths: { masterslider: 'js/masterslider.min', }, shim: { masterslider: { deps: ['jquery'] } } };

  4. Add masterslider.css to app/design/frontend/My-vendor/my-name-theme/web/css/source

  5. Use or create file _extend.less to app/design/frontend/My-vendor/my-name-theme/web/css/source Write in _extend.less this in the last row: @import 'masterslider.css';

  6. cd /var/www/domain/html rm -rf pub/static/* rm -rf var/view_preprocessed/* php /var/www/domain/html/bin/magento cache:clean php /var/www/domain/html/bin/magento setup:static-content:deploy en_US ru_RU php /var/www/domain/html/bin/magento cache:clean

  7. Call slider in content home page or in file phtml like this:

<script>

    require([
        'jquery',
        'masterslider'
    ], function($) {
        jQuery(document).ready(function() {
            jQuery('#masterslider').show().masterslider({
            /* code slider */
            });
        });
    });

</script>