Skip to content

Commit 5f526c4

Browse files
authored
feat: use window.Swal if defined (#3)
* feat: use window.Swal if defined * chore: add docs
1 parent 009ee4d commit 5f526c4

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

README.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,15 @@ Simple and straightforward:
8686
- The `Swal::fire()` method will pass the options to the [flashed session](https://laravel.com/docs/12.x/session#flash-data).
8787
- The blade partial template will check if there are any flashed session data and will render the SweetAlert2 popup.
8888
89-
### 3. Any limitations?
89+
### 3. How does the SweetAlert2 JavaScript library loading work?
90+
91+
This package uses a smart loading strategy for the SweetAlert2 library:
92+
93+
1. **Check for existing SweetAlert2**: If `window.Swal` is already available, it will use the existing instance.
94+
95+
2. **Dynamic CDN loading**: If SweetAlert2 is not loaded, it will dynamically import it from the official CDN (`https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.esm.all.min.js`).
96+
97+
### 4. Any limitations?
9098
9199
SweetAlert2 is a JavaScript package and some of its options are JS callbacks. It's not possible to use them in the `Swal::fire()` method.
92100
If you need to use JS callbacks, you have to go to JS and use the SweetAlert2 API directly.

resources/views/index.blade.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,24 @@
11
@if (session()->has('sweetalert2'))
22
<script type="module">
3-
import Swal from 'https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.esm.all.min.js';
3+
const loadSweetAlert2IfNeeded = async () => {
4+
// If SweetAlert2 is already loaded, use it
5+
if (window.Swal) {
6+
return window.Swal;
7+
}
48
9+
// Otherwise, dynamically import it from CDN
10+
try {
11+
return (await import('https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.esm.all.min.js')).default;
12+
}
13+
14+
// Fallback in case of an error (e.g., network issues)
15+
catch (error) {
16+
console.error('Failed to load SweetAlert2:', error);
17+
return { fire: () => {} };
18+
}
19+
};
20+
21+
const Swal = await loadSweetAlert2IfNeeded();
522
Swal.fire(@json(session('sweetalert2')));
623
</script>
724
@endif

0 commit comments

Comments
 (0)