diff --git a/src/react-script-hook/index.test.tsx b/src/react-script-hook/index.test.tsx index 10920a21..913b3b71 100644 --- a/src/react-script-hook/index.test.tsx +++ b/src/react-script-hook/index.test.tsx @@ -272,4 +272,26 @@ describe('useScript', () => { expect(document.querySelectorAll('script').length).toBe(1); }); }); + + it('should remove script from DOM and scripts cache when unmounted during loading', () => { + expect(document.querySelectorAll('script').length).toBe(0); + expect(Object.keys(scripts).length).toBe(0); + + const testSrc = 'http://scriptsrc/test'; + const { unmount } = renderHook(() => useScript({ src: testSrc })); + + // Verify script was added + expect(document.querySelectorAll('script').length).toBe(1); + expect(Object.keys(scripts).length).toBe(1); + expect(scripts[testSrc]).toBeDefined(); + expect(scripts[testSrc].loading).toBe(true); + + // Unmount the component while script is still loading (before load event) + unmount(); + + // Verify script was removed from DOM and cache + expect(document.querySelectorAll('script').length).toBe(0); + expect(Object.keys(scripts).length).toBe(0); + expect(scripts[testSrc]).toBeUndefined(); + }); }); \ No newline at end of file diff --git a/src/react-script-hook/index.tsx b/src/react-script-hook/index.tsx index 8371eb19..acbcc5a6 100644 --- a/src/react-script-hook/index.tsx +++ b/src/react-script-hook/index.tsx @@ -131,7 +131,7 @@ export default function useScript({ // but only applied when loading if (status && status.loading) { scriptEl.remove(); - delete exports.scripts[src]; + delete scripts[src]; } }; // we need to ignore the attributes as they're a new object per call, so we'd never skip an effect call