Jquery working inside CodePen but not inside Visual Studio Code

You’re loading your script at the very top of the body, before the rest of the page. You can solve your issue by moving the script to the bottom (right before the closing </body> tag), or by adding type="module" instead of type="text/babel", or by wrapping your code inside a DOMContentLoaded event listener.

I’m not entirely certain what’s happening, but Babel has nothing to do with this. If the browser sees a script tag with a type attribute, it seems the script is loaded at a different time, after the rest of the page is parsed.

1 Like

Without the babel script, adding type="text/babel" will not make it work. In fact, it will make the script not load at all (it makes it a data block, as far as I can tell).

script

type

Any other value: The embedded content is treated as a data block which won’t be processed by the browser. Developers must use a valid MIME type that is not a JavaScript MIME type to denote data blocks. The src attribute will be ignored.

This is why you do not get any errors and I’m guessing how the compiled code and the original code do not trample each other.

Either by the time babel has compiled and added the code to the script tag in the head the DOM has finished loading, or it’s just the way it gets compiled and added that makes sure the DOM is ready (or it might just be a lucky outcome of a “race condition”).

1 Like

Yeah I just added the <script type="module" src='./index.js'></script>
and it fixed the issue.
There is no need for Babel.
And what does the type="module" mean?
Thanks!

Yeah I believe it was just a pure luck.

If you have a very large JavaScript file for your website, it allows you to split the code up into smaller units/files. Each file can import and export functionality from and to another file, you could have a file where you make calculations, one for manipulating the DOM, etc. React is a good example for how JS code can be split up into smaller units (or components).

The reason why it made your code work is that a script with type="module" is automatically deferred (means that the script isn’t processed by the browser before the whole document is parsed). Since you don’t actually have a module, it would make more sense to remove type="module" and instead add defer to achieve the same effect:

<script src='./index.js' defer></script>

2 Likes

Wow, I learned a lot from solving one small problem like this.

Thanks again.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.