2

I need to load two versions of the same library from CDN. Is there a way to specify the name of the resulting object on window so that they don't clash? Or can I rename the first before the second loads?

Qwerty
  • 29,062
  • 22
  • 108
  • 136

2 Answers2

2
<script src="lib@1" />
<script> window.lib1 = window.lib; </script>
<script src="lib@2" />

then

window.lib1 // is lib@1
window.lib  // is lib@2
Qwerty
  • 29,062
  • 22
  • 108
  • 136
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Wouldn't it be the other way? Aren't you assigning the result of `src=lib1` to `window.lib2` in your code here? – TKoL Nov 11 '19 at 14:08
  • What about async/defer? Can that be handled? – Qwerty Nov 11 '19 at 14:11
  • 2
    @Qwerty I think if you defer EVERY script element above, they execute in order after the rest of the page loads, so that should be okay. – TKoL Nov 11 '19 at 14:17
0

Based on Jonas Wilms' answer, I came up with these two solutions when using webpack, which I have not mentioned in the original question.

here is a Demo https://codesandbox.io/s/multiple-library-versions-kvg5d

webpack - externals

  • you must change webpack config when updating a package
module.exports = {
  externals: {
    react: 'React16_11'
  }
};

in code

import React from 'react' // webpack translates to window.React16_11

webpack - aliases*

  • you must change a .js file in project when updating a package
module.exports = {
  alias: {
    react$: './getReactFromWindow',
  },
};

getReactFromWindow.js:

 module.exports = window.React16_11;

in code

import React from 'react' // webpack translates to './getReactFromWindow'

*webpack aliases based on this question

Qwerty
  • 29,062
  • 22
  • 108
  • 136