[react/펌글] 외부 자바스크립트 파일을 동적으로 로딩 하기 (loading external javascript file dynamically in react)

By | 4월 18, 2023

원문 출처


script loader as a module

const loadGMaps = (callback) => {
  const existingScript = document.getElementById('googleMaps');
  if (!existingScript) {
    const script = document.createElement('script');
    script.src = 'https://maps.googleapis.com/maps/api/js';
    script.id = 'googleMaps';
    document.body.appendChild(script);
    script.onload = () => { 
      if (callback) callback();
    };
  }
  if (existingScript && callback) callback();
};
export default loadGMaps;


적용

import React, { useEffect, useState } from 'react';
import GoogleMap from '../GoogleMap';
import loadGMaps from '../scripts/loadGMaps.js';
const Maps = (props) => {
  const [loaded, setLoaded] = useState(false);
  useEffect(() => {
    loadGMaps(() => {
      setLoaded(true);
    });
  });
  return (
    <div className="maps-component">
      {loaded ? <GoogleMap /> : ''}
    </div>
  );
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments