2

I want to add lazy load js file in custom module.

In templates folder in that web/js/lazy_load.js file I have put.

Then in layout file

  <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">

<head>
    <title>Pest Library</title>
    <script src="js/jquery.lazyload.js"/>
</head> 

<body>

    <referenceContainer name="content">
        <block class="Iksula\PestLibrary\Block\Index\Index" name="pestlibrary_index_index" template="Iksula_PestLibrary::pestlibrary_index_index.phtml"/>
    </referenceContainer>

</body>
</page>

But js file is not called.

1
  • please let me know if you have issue. Aug 1, 2017 at 4:35

2 Answers 2

2

If you want to add js in your custom module using layout then you need to write below code :

 <head>
       <script src="Iksula_PestLibrary::js/jquery.lazyload.js"/> 
</head>

After that run php bin/magento setup:static-content:deploy command

But as per magento 2 standards use require-js concept to include js

Create requirejs-config.js in app/code/Iksula/PestLibrary/frontend/requirejs-config.js

Below is the code using requirejs-config.js :

var config = {
    map: {
        '*': {
            lazyloadScript:'Iksula_PestLibrary::js/jquery.lazyload'
        }
    }
};

then call js in your template file: app/code/Vendorname/modulename/templates/custom_js.phtml

<script>// <![CDATA[
    require([
        'jquery',
        'lazyloadScript'
    ], function ($, script) {
        //Your code here
        //alert('Here');
    });
    // ]]>
</script>
0

You are forgot first line and also assigned modulepath for your js file.

<?xml version="1.0" encoding="UTF-8"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
    <title>Pest Library</title>
    <script src="Iksula_PestLibrary::js/jquery.lazyload.js"/>
</head>
<body>
    <referenceContainer name="content">
        <block class="Iksula\PestLibrary\Block\Index\Index" name="pestlibrary_index_index" template="Iksula_PestLibrary::pestlibrary_index_index.phtml"/>
    </referenceContainer>
</body>
</page>

Run php bin/magento setup:static-content:deploy command

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.