3

Is it possible to load external jQuery from CDN when it needed like in RequireJS? I mean specify external jQuery source (on CDN) somewhere in config and then use it in CommonJS (or AMD) style:

$ = require('jquery')

The problem is I have my custom script above the jQuery's CDN link and so I have 'can't find variable jQuery' error. Schematically my code looks like:

<script src="custom_code.js'>
  // uncompiled source like:
  define(['jquery', '../../node_modules/baconjs/dist/Bacon.js'], function($, bacon) {
    console.log 'ok'
  });
</script>
...
<script src="//yastatic.net/jquery/2.1.3/jquery.min.js"></script> 
Dmitrii Dushkin
  • 3,070
  • 4
  • 26
  • 37

1 Answers1

0

After reading this post, and with the use of require.ensure I've managed to get it work. custom_code.js:

require.ensure(['jquery', '../../node_modules/baconjs/dist/Bacon.js'], function(require){
  var $ = require 'jquery'
  var bacon = require '../../node_modules/baconjs/dist/Bacon.js'

  $('.content').prepend('it works!')
});

and in webpack config I've added

externals: { jquery: "jQuery" },

In this case webpack will make additional request for compiled bundle with Bacon.js.

Still I wonder what will be if client loads Bacon.js before jQuery will be loaded from CDN?

Community
  • 1
  • 1
Dmitrii Dushkin
  • 3,070
  • 4
  • 26
  • 37
  • I would very much like an answer to your last question: "Still I wonder what will be if client loads Bacon.js before jQuery will be loaded from CDN?" It is the problem I am having. – Brian May 16 '16 at 21:17
  • 2
    Found it--The answer to that question is to use something like the `scriptjs` package. – Brian May 16 '16 at 21:21