Javascript not loading properly in LiveView

I am using dataTables <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> in my app for creating and manipulating table.

And I included the dataTable script at the top of my index.html.eex file and everything is working fine.

Now when I converted my app to use LiveView, in which I renamed the index.html.eex to index.html.leex , dataTables javascript is behaving very weirdly. Sometimes the dataTables gets displayed properly as expected and sometimes not.

Below is my 2 snippets

As you can see the above 2 snippets is very different. The first is the one which displays properly and second one not displaying properly.

Below is my code in index.html.leex

<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

Some Html in between

<script>
$(document).ready(function (){
   var table = $('#example').DataTable({
     "paging": false,
     "info": false,
      'columnDefs': [{
         'targets': 0,
         'searchable':false,
         'orderable':false,
         'className': 'dt-body-center',
         'render': function (data, type, full, meta){
             return '<input type="checkbox" name="id[]" value="'
                + $('<div/>').text(data).html() + '">';
         }
      }],
      'order': [1, 'asc']
   });
});

</script>

Not sure whether the dataTables script is not loading properly or we need to include the dataTables script somewhere else.

HTML5 specifies that a <script> tag inserted with innerHTML should not execute.


Update:


Aside: Phoenix 1.4 uses webpack as a bundler and LiveView itself uses modular JavaScript - so I wouldn’t recommend mixing that with non-modular JavaScript - even it it seems to work in the short term.

1 Like