S
S
Sergey Sokolov2018-07-23 16:56:10
JavaScript
Sergey Sokolov, 2018-07-23 16:56:10

How to specify an alternative source (fallback) for external CDN modules in webpack?

I am migrating a project from RequireJS to webpack. In the old config, some of the libraries are loaded from external sites: Yandex.Metrica, VK scripts, and others. For a third of visitors, advertising is cut and these scripts will not work. In this case, empty path fallbacks with called methods are substituted. For example, for Yandex.Metrica, the following config:

requirejs.config({
  paths:
    "yametrika": [ "//mc.yandex.ru/metrika/watch", "lib/yamertika_dummy"],

In the require code, metrics are called and Metrika.params(), Metrika.reachGoal()etc. are called. In case AdBlock or similar didn't miss Metrica scripts, empty methods in the stub are called.
So far, webpack has found only the externals section , where you can specify modules that are not included in the bundle.
Probably, it would be possible to wrap each method call of Metrica in try{..} catch(). But I would like to substitute my alternative.
What is the best way to deal with the possibility of blocking the loading of some of these modules?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2018-07-24
@sergiks Asker

Haven't tried it on a working project yet, just going with my thoughts.
Looks like you just need to load the gags as polyfills. See the Loading Polyfills documentation .

  1. Move gag codes to a separate polyfills.js file
  2. In the webpack config, specify one or more entry points for the polyfill(s):
    entry: {
      polyfills: './src/polyfills.js',
      index: './src/index.js'
    },

  3. ..and another output:
    output: {
      filename: '[name].bundle.js',
      // создаст polyfills.bundle.js и index.bundle.js

  4. In the HTML of the page, before the tag of the main bundle, insert an attempt to load the Metrica and check its loading. In case of failure, load the polyfill bundle:<script>
    <script src="https://mc.yandex.ru/metrika/watch.js"></script>
    <script>
    if( !(Ya in window)) {
      var scriptElement = document.createElement('script');
    
      scriptElement.async = false;
      scriptElement.src = '/polyfills.bundle.js';
      document.head.appendChild(scriptElement);
    }
    </script>

    Those. the point is to prepare one or more additional. bundles with plugs and load them based on the results of checking the loading of CDN scripts, before loading the main bundle.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question