I have a module, and I want to add a javascript generated in the module at the frontend footer.
The javascript has to be built dynamically because it depends on server variables. I've thought of a phtml
.
How do I add this?
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:
'use strict';
require(["jquery", "domReady!"], function($){
$(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>
I suggest not to use global variables if you need data from the server. You can pass them in other way, for example using the widget factory of jQuery UI.
In your phtml do something like:
<div id="element"></div>
<script type="text/x-magento-init">
"#element": {
"yourJsModule": {
"data1": <?php echo $variable ?>,
"data2": <?php echo $variable2 ?>
}
}
</script>
In your javascript
define([
"jquery"
], function($){
$.widget('vendor.module', {
_create: function() {
//Here your variables
console.log(this.options);
}
});
return $.vendor.module;
});
Add your js via require.config.js:
var config = {
map: {
'*': {
yourJsModule: 'Namespace_Module/path/javascript'
}
}
};
You can do the same as follows
<referenceContainer name="before.body.end">
<block class="\Magento\Framework\View\Element\Template" template="Namespace_Modulename::before.phtml" name="before_body_js"/>
</referenceContainer>
In before.phtml file add your code.