I'm trying to load the datatables javascript library in a plugin that I'm writing. The issue is that I get a conflict when I load the external resource, because datatables is conflicting with something when I call require.
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/jquery.dataTables.min.js"></script>
...
<script type="text/javascript">
require(['forum/admin/footer']); <-- crashes here, line 281
</script>
Here's the error message:
Uncaught Error: Mismatched anonymous define() module: function (h){var j=function(e){function o(a,b){var c=j.defaults.columns,d=a.aoColumns.length,c=h.extend({},j.models.oColumn,c,{sSortingClass:a.oClasses.sSortable,sSortingClassJUI:a.oClasses.sSor...<omitted>...ch require.js:8
B require.js:8
M require.js:15
d require.js:26
requirejs require.js:31
(anonymous function) (index):281
Since this is a plugin, I have restrictions I'm trying to work around, such as not being able to call require.config() at the beginning to specify paths for resources. I saw someone use the define
call like
define('resource', ['http://cdn.ajax.blah']);
in this blog
but it doesn't look like it can be used that way since every other example has a function as a 2nd parameter.
The method used in the question does not work because DataTables is AMD-aware. If it detects that there's an AMD-style loader (which RequireJS is), then it defines itself as a module. However, it is invalid for AMD modules to be loaded with <script>
, hence the error message.
The module in forum/admin/footer
should be defined so as to require DataTables:
define([...,
'//cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/jquery.dataTables.min.js'],
function (...) {
});
(There's no need for a parameter corresponding to the DataTables module since it is a jQuery plugin.)
A few additional notes regarding the wider issue of integrating this plugin in a site that has already configured RequireJS:
require.config
could be called multiple times to add configuration. However this may be deemed unacceptable if no coordination is expected between the plugin and the main code.
RequireJS has a notion of context. The documentation talks about it for loading multiple versions but maybe it can be fruitfully adapted to allow a plugin-specific configuration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With