Magento – Add jQuery Datatables in magento 2

jquerymagento2requirejs

I am trying to use the jquery DataTables in magento-2 frontend using the requirejs.
I can see the datables.min.js file in the net panel,
enter image description here

but somehow it give the following error.
enter image description here

My reuirejs-config.js looks like this

var config = {
    map: {
        '*': {
            dataTable: 'Ktpl_Slider/js/datatables.min'
        }
    }

};

And i am calling this function in a template file as follows

<script type="application/javascript">
    requirejs(['jquery','dataTable'],function($){
        $(document).ready(function(){
            $('#list-table').DataTable();
        });
    });
</script>

I guess there is problem with the order of loading the js files. i tried with shim configuration but that did not work, maybe there was some mistake in the shim configuration

Best Answer

I think that you have another problem in your script. you have defined both jquery and datatable as dependencies. But you only pass jquery to the function. The function part of the requirejs script should have the dependency scripts object passed to the function part. try:

<script type="application/javascript">
requirejs(['jquery','dataTable'],function($, dataTable){
    $(document).ready(function(){
        $('#list-table').DataTable();
    });
});

As for the shim part, I think that if you have defined it something like :

var config = {
    map: {
        '*': {
            dataTable: 'Ktpl_Slider/js/datatables.min'
        }
    },
    "shim" {
        "dataTable" : ["jquery"]
    }
};

then it's fine. Looks like it works for me, however, the extra quotes around "shim" are only present in Magento 2 documentation, and not in requirejs documentation. so not sure which one is right.

Related Topic