I use svelte 3 with datatables.js and jquery.js in browser only (not ssr).
After datatables make ajax request and try to create table I got error:
Uncaught TypeError: Cannot read properties of undefined (reading 'createElement')
at _fnCreateTr (jquery.dataTables.js:3160)
In firefox error was: Uncaught TypeError: document is undefined .
With chrome debuger I see that document == undefined .
How is posible that document is not defined in browser?
My code is:
<script lang="ts">
import {onMount, tick} from "svelte";
import jQuery from 'jquery'
import dt from 'datatables.net-dt'
import {flatten, SITE_URL} from "../config";
import fixJquery from "../includes/jquery.spring-friendly";
dt(jQuery)
function handleError(xhr, error, thrown) {
console.error("ERROR", xhr.responseText);
}
fixJquery(jQuery);
onMount(async () => {
await tick();
jQuery(document).ready( function () {
let dataTable = jQuery("#example").DataTable(
{
processing: true,
serverSide: true,
ajax: {
url: SITE_URL + "/users/datatables",
type: "GET",
error: handleError
},
columns: [
{
data: 'id'
},
{
data: 'name'
}
],
}
);
});
});
</script>
<div>
<h2>User list</h2>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Here is Svelte REPL with this problem: svelte.dev/repl/8354f4daadc04165a59dbac5be41e253?version=3.44.2
Depending on how you load DataTables library, it may see a different scope of the world and differently initialised jQuery. I encountered this issue before. Thus, it is better to explicitly initialise DataTables and pass jQuery and its document to it.
Here is some of our open source code that is using Svelte + DataTables (+ its jQuery dependency)
You can see the live website here using Svelte + DataTables.