Jump to content

Problem with global functions using Vite


maxxd

Recommended Posts

Hi y'all.

I think I'm having a senior moment; I have the following code in `app.js`:

import Swal from 'sweetalert2';
window.Swal = Swal;

`app.js` is included in my blade templates, where I have a partial that includes this code:

<script>
console.log(window);
console.log(window.Swal);
</script>

My console output is attached to this post. Note that apparently nothing is attaching to the window object - even if it's just a simple `window.st = "testing";`, that reports undefined as well.

js-issue.png

Link to comment
Share on other sites

I think this is due to your partial running too soon and the console logging being lazy-loaded.  At the time you log, window.Swal does not exist (as indicated by the undefined).  The debug tools don't evaluate the full properties until you click the expand triangle next to Window and at that time window.Swal has been created.

Likely this is due to the fact that all JS modules are deferred by default.  Your logging code runs as soon as it's parsed, but deferred modules don't run until just before the DOMContentLoaded event is fired which happens after everything else is parsed.

If you change your logging to this, it should show up:

<script>
window.addEventListener('DOMContentLoaded', ()=>{
	console.log(window.Swal);
});
</script>

 

Edited by kicken
Link to comment
Share on other sites

I thought it might be loading order so I moved things around in my blade template, but that didn't seem to make a difference. Admittedly, I didn't know that console logging was lazy-loaded and I thought you had to specifically declare a script include as type="module" for it to be deferred without the `deferred` attribute being set but that all makes a ton of sense and it's a great place to start looking; gotta admit if it is as simple as wrapping everything in a loaded event I'm gonna be pretty red-faced while saying thanks!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.