Load external scripts with requirejs without access to config

笑着哭i 提交于 2019-12-12 07:48:40

问题


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.


回答1:


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:

  1. 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.

  2. 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.




回答2:


Have you just tried a simple:

require(['//cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/jquery.dataTables.min.js']);

It works for local files without a doubt.



来源:https://stackoverflow.com/questions/21624503/load-external-scripts-with-requirejs-without-access-to-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!