Home > Mobile >  How do I get a js library without import
How do I get a js library without import

Time:12-05

I want to make a js library, and I have all the code. Libraries like Jquery can let you do like

<script src = "..."></script>
<script>
//uses the library
</script>

without the import * from JQuery. How can I do this without declaring the library a modular or importing?

CodePudding user response:

Assign the top-level object to a property on window, just like jQuery does:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// testing jQuery:
console.log(window.$);
console.log(window.jQuery);
console.log($); // same as window.$
console.log(window.jQuery === $);
</script>

<script>
// your module (imagine this was hosted and loaded via the "src" attribute like jQuery)

const myMath = {};

myMath.add = (...numbers) => numbers.reduce((sum, n) => sum   n, 0);

window.MY_MATH = myMath;
</script>
<script>
// use myMath

const {add} = window.MY_MATH;

console.log(add(1, 2, 3, 4)); // 10
</script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related