0

I'm building a module and I need to load Javascript that must be generated in my module (NO theme) to the shop frontend.

Then, when a user enters on the web, the module has to generate js and inject to the shop frontend.

The js has variables that I have in the database, then I need to join it with a Block and PHTML to create it.

How can I do it?

0

1 Answer 1

1

You just need to add these files:

ModuleVendor/ModuleName/view/frontend/layout/default.xml

or

ModuleVendor/ModuleName/view/frontend/layout/<frontName>_<controllerName>_<actionName>.xml

File content:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="ModuleVendor_ModuleName/js/my_js.js"/>
    </head>
</page>

JS file:

ModuleVendor/ModuleName/view/frontend/web/js/my_js.js

JS Content:

require([
    "jquery"
], function($){
//<![CDATA[
    $(document).ready(function() {
        console.log('jquery loaded with success!');
    });
//]]>
});

To add some controller or block you can add the JS content above using a PHTML:

<referenceContainer name="before.body.end">
    <block class="\Magento\Framework\View\Element\Template" template="Namespace_Modulename::my_js.phtml" name="my_js"/>
</referenceContainer>
2
  • how can i call controller or block from my_js?
    – Miguel
    Commented May 29, 2017 at 16:13
  • you can do it using jquery ajax call Commented May 29, 2017 at 17:52

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