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!
- Path:
app/design/frontend/My-vendor/my-name-theme/web
- Add
masterslider.min.js
toapp/design/frontend/My-vendor/my-name-theme/web/js
Create
requirejs-config.js
toapp/design/frontend/My-vendor/my-name-theme
var config = { paths: { masterslider: 'js/masterslider.min', }, shim: { masterslider: { deps: ['jquery'] } } };
Add masterslider.css to
app/design/frontend/My-vendor/my-name-theme/web/css/source
Use or create file
_extend.less
toapp/design/frontend/My-vendor/my-name-theme/web/css/source
Write in_extend.less
this in the last row:@import 'masterslider.css';
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
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>