'How to import OldSchool scripts into ES6 app

Old scripts designed to be used directly with < script > tag, use various global variables and some features which don't work inside ES6 with default strict mode.

For Example:

Uncaught TypeError: Failed to execute 'importScripts' on 'WorkerGlobalScope': Module scripts don't support importScripts().

How can we hypothetically do something like this:

var coolModule = magicImport( 'oldstyle_library.js' )

Or better yet:

var coolIsolatedModule = magicImportWrapContain( 'oldstyle_library.js' )

The desired outcome is some way to import ES5 or old style javascript into a neatly isolated object just like ES6 import module. Wild and weird solutions welcome.



Solution 1:[1]

Create a script DOM element, set the script src, insert it into body. do next in event 'onload'.it's like

const script = document.createElement("script");
script.src = 'oldstyle_library.js';
script.onload = function() { //get the library exports here };
document.body.appendChild(script);

but it's asynchronous.You can use Promise to implement the magicImport function.

One implement for example:

function magicImport(src, globalVar) { 
  return new Promise(resolve => {
     let exports = window[globalVar];
     if(exports) {
        resolve(exports);
     } else {
        const script = document.createElement("script");
        script.src = src;
        script.onload = function() { resolve(window[globalVar]); };
        document.body.appendChild(script); 
     }
  });
}

magicImport("jquery.js", "jQuery").then(jQuery => { 
   //do what you want with jQuery
});
// or use async/await
const jQuery = await magicImport("jquery.js", "jQuery");
//do what you want with jQuery

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1