Search code examples
javascriptjquerydatatablescdnfallback

CDN fallback for DataTables.js


I am trying to write a CDN fallback for datatables.min.js -- somehow, I couldn't find any on Google or on datatables.net. After reading this StackOverflow post and this DataTables post, I came up with this unsuccessful piece (even tried various expressions as shown):

<script>
    if (typeof jQuery.fn.dataTable === 'undefined') {
        document.write('<script src="~/scripts/datatables.min.js"><\/script>');            
        //document.write('<script src="~/scripts/datatables.min.js">\x3C/script>'); //same
        //document.write('\x3Cscript src="~/scripts/datatables.min.js"\x3E\x3C/script\x3E'); //same
    }
</script>

For troubleshooting, I loaded datatables.min.js directly and got these two confusing results:

1/ I get undefined (BAD) from this:

<script>
    document.write('<script src="~/scripts/datatables.min.js"><\/script>');
</script>
<script>
    alert(typeof jQuery.fn.dataTable);
</script>

2/ ... but somehow I get function (GOOD) from that:

<script src="~/scripts/datatables.min.js"></script>
<script>
    alert(typeof jQuery.fn.dataTable);
</script>

That looks the same to me, especially since document.write uses synchronous loading. I also tried a pure DOM method but no luck.

What am I missing with document.write?


Solution

  • A correct CDN fallback for DataTables following accepted fallback practices is:

    <script>
        if (typeof jQuery.fn.dataTable === 'undefined') {
            document.write('\x3Cscript src="/scripts/datatables.min.js"\x3E\x3C/script\x3E');
            //document.write('<script src="/scripts/datatables.min.js"><\/script>');
        }
    </script>
    

    or simply

    <script>window.jQuery.fn.dataTable || document.write('\x3Cscript src="/scripts/datatables.min.js"\x3E\x3C/script\x3E')</script>
    

    The tilda / relative path in src="" was the problem, as suggested by @ParthTrivedi (see comments). Per this post, "when in script, paths are relative to displayed page".