Datatable not always initialized

Datatable not always initialized

j.castellij.castelli Posts: 10Questions: 4Answers: 0

Hello everyone,

Quite frequently but not all the time I have this error:

Uncaught (in promise) TypeError: $(...).DataTable is not a function at initDatatable

From what I can tell, I think it happens when the datatable is being initialized but the CDN script is not fully loaded yet.
Do you know if there's a way for me to wait for it to be ready before initializing my table?

Thanks!

Answers

  • kthorngrenkthorngren Posts: 21,459Questions: 26Answers: 4,975
  • j.castellij.castelli Posts: 10Questions: 4Answers: 0

    The thing is I already use it. Here's how the table is initialized in my script:

    document.addEventListener("DOMContentLoaded", function(event) {
        if(document.querySelectorAll("#datatableStorefront").length) {
            (async () => {
                let columnsData = await fetch(routes.getStorefrontsDatatableColumns).then(response => response.json()).catch(console.log);
                initDatatable(columnsData); // This function initializes my table with data I got from the previous request
            })();
        }
    });
    

    Here's how my scripts are loaded:

    <!-- This first script loads JQuery as well  -->
    <script src='https://adminconnect.xxx.org/V3/US_AdminConnect_SDK.js'></script>
    <script defer src="https://cdn.datatables.net/v/dt/(...)/datatables.min.js"></script>
    <script src="{{ asset('js/app.js') }}"></script>
    

    There's indeed a defer before the CDN script but if I remove it, then I have an error saying that JQuery is not loaded.

    To be honest I'm pretty much a noob when it comes to JavaScript, do you think there's a way to overcome this?

  • kthorngrenkthorngren Posts: 21,459Questions: 26Answers: 4,975
    edited January 2022

    document.addEventListener("DOMContentLoaded", function(event)

    This is according to the DOMContentLoaded event docs:

    The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
    A different event, load, should be used only to detect a fully-loaded page.

    Maybe this SO Thread will help. A better place to research generic Javascript and jQuery questions is on Stack Overflow.

    Kevin

Sign In or Register to comment.