react-use icon indicating copy to clipboard operation
react-use copied to clipboard

Feature request: useScript

Open Falci opened this issue 5 years ago • 4 comments

Is your feature request related to a problem? Please describe. Problem: I'd like to dynamically import scripts as <script> tags.

Describe the solution you'd like Proposal:

const useScript = ({ url, id, type = 'text/javascript', async = true }) => {
    const [ready, setReady] = React.useState(false);
    const [failed, setFailed] = React.useState(false);

    React.useEffect(() => {
        if (document.getElementById(id)) {
            return;
        }

        const element = document.createElement('script');

        element.src = url;
        element.type = type;
        element.async = async;
        element.id = id;

        setReady(false);
        setFailed(false);

        element.onload = () => setReady(true);

        element.onerror = () => {
            setReady(false);
            setFailed(true);
        };

        document.head.appendChild(element);

        return () => {
            document.head.removeChild(element);
        };
    }, [url, id]);

    return { ready, failed };
};

Describe alternatives you've considered I'm using this the code above directly in my project.

Falci avatar May 29 '20 09:05 Falci

Maybe also on top of that we could build a makeScript helper that defines script at module scope.

const useMyScript = makeScript({ url, id, type, async });

useMyScript.preload();

const Demo = () => {
  const { data, error, isLoading } = useMyScript();
};

.preload() could initiate loading already at module scope.

streamich avatar Jun 03 '20 17:06 streamich

I will do it ~

myamolane avatar Aug 04 '20 02:08 myamolane

For someone who need this feature right now. https://usehooks.com/useScript/

ctrngk avatar Nov 11 '20 03:11 ctrngk

Maybe also on top of that we could build a makeScript helper that defines script at module scope.

const useMyScript = makeScript({ url, id, type, async });

useMyScript.preload();

const Demo = () => { const { data, error, isLoading } = useMyScript(); }; .preload() could initiate loading already at module scope.

https://github.com/streamich/react-use/pull/1444

Could you merge this? Other hook libraries already support this function.

gracefullight avatar Mar 14 '25 02:03 gracefullight