Import module after function . load() from jQuery

Asked

Viewed 91 times

-1

Because it is not possible to import a module after loading an external content by jQuery.load(), from what I understand it needs to be outside the scope, but outside the scope the content of the script is not read, resulting in the error message:

Uncaught Syntaxerror: import declarations may only appear at top level of a module

The module has already been loaded on the page and works in the calls of the existing buttons, but it is not recognized in the content created in the DOM, so I thought it would be possible, but not.

Maybe there is another way to link the function to external content loaded, but what I tried was below resulting in error.

$(document).ready(function(){
    $(document).on('click','button.btn-load-items',function( event ) {          
        event.preventDefault();
        let token = $(this).data('category');
        $( 'div#load' + token ).load( 'load-items.php?token=' + token, function (e) {
            $( 'div.load-images' + token ).hide();
            $("html, body").animate({ scrollTop: $('div#load'+token).offset().top - 50 }, 500, function() {
                
                $.getScript("assets/js/velocity.min.js", function() {
                    console.log('ok');
                });
                
                /* ---------------------- AQUI -------------------------- */
                import QuantityInput from './assets/vendors/quantity-button/quantity.js';

                (function(){
                    let quantities = document.querySelectorAll('[data-quantity]');
                    if (quantities instanceof Node) quantities = [quantities];
                    if (quantities instanceof NodeList) quantities = [].slice.call(quantities);
                    if (quantities instanceof Array) {
                        quantities.forEach(div => (div.quantity = new QuantityInput(div, 'Down', 'Up')));
                    }
                })();
            });
        });
    });
});

1 answer

1


So I made a quick example for you to use...

From what I saw fast in your script, does not follow the standards of import, from what I know the way you used should be started the script and not put in the body of a js script, I went through it at the beginning, so I discovered this, you can matter this way...

Links to study, MDN - import

Obs: this technique is well below in pg. of MDN. Good study!

const

// ARMAZENARA AS FUNCOES/METODOS CARREGADOS
MODULOS = {},

fc_import_m = async function (arg = false) {

  // CONDICAO CHECO VALOR DO ARG RECEBIDO
  if (!arg)

    // FUNCAO return FINALIZA PROCESSO
    return;

  // FUNCAO IMPORT MODULOS
  await import((typeof arg === 'object' && arg.hasOwnProperty ('a') ? arg.a : arg)).then((argM) => {
  // FUNCAO .then PARA RETORNO DA PROMESSA

    // LOOP PARA LISTAGEM E ARMAZENAMENTO
    for (let argV in argM) {

      // CONDICAO CHECA SE O ARMAZENAMENTO DEVE SER A PARTIR DE UMA NOVA PROP. PAI PARA VARIADOS METODOS DO MODULO
      if (typeof arg === 'object' && arg.hasOwnProperty ('m')) {

        // CONDICAO CHECA SE A PROP. JA EXISTE
        if (!MODULOS.hasOwnProperty (arg.m))

          /*
          SETO OBJ

          MODULOS[(arg.m]: obj, propriedades e valores armazenados do mudulo recebido
          */
          MODULOS[arg.m] = {};

        /*
        SETO OBJ

        MODULOS[(arg.m][argV]: obj, propriedades e valores armazenados do mudulo recebido
        */
        MODULOS[arg.m][argV] = argM[argV];

      } else {

        /*
        SETO OBJ

        MODULOS[(argV]: obj, propriedades e valores armazenados do mudulo recebido
        */
        MODULOS[argV] = argM[argV];

      }

    }

  }).catch ((argE) => {
  // FUNCAO .catch PARA RETORNO COM FALHA DA PROMESSA

    // FUNCAO throw ENVIA UM TypeError NOTIFICANDO
    throw new TypeError(`! error: contate suporte caso continue ${argE}`);

    // FUNCAO return FINALIZA PROCESSO
    return;

  });

};


/*
NomeModulo, opcional, remover caso queira que o nome da funcao no modulo seja setada
*/
fc_import_m ({m: 'NomeDoModulo', a: './modulo.js'});

fc_import_m ('./modulo.js');

  • Only one Obs: if you have any error in the syntax of the module to be loaded it will fall in the catch.

  • 1

    Hi, thanks for your wisdom and good will, you have some reference study on scopes, and could also tell me if, using Babel/webpack this helps to globalize(sic) my codes and better deal with this scenario?

  • 1

    @Eliseub. so this is quite complex, I don’t know how and the structure of your system but try to use a root/parent context, you are already using the IIFE technique this is important, so you will be able to avoid that your imported modules and methods are exposed globally, then you do something dynamic, use the import this way and very powerful, you still use the jQuery that is a hand on the wheel, love very much! In the matter of context/scopes and studies, I always use Google, MDN w W3schools, but MDN has helped me a lot, from a while ago Stackoverflow also...

  • 1

    continuing, the big key/secret and the set you use, its structure, the skeleton of your system. For years I have been working on a system, after some 3 years repeating many index.js files I saw that I could load the world with just one call ajax and an index.js... hahaha, it’s laborious but it’s worth it. See the structure how you can align to reuse methods, make it a private context. All this roughly as I said, is complex, solve your problems with simple scripts always, then focus on security, performance and intelligence/ simplicity... time king! = D

  • 1

    In the Babel/webpack issue I never used, I can’t tell you, for nothing, I’m happy to help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.