简体   繁体   中英

Load script synchronously from dynamically generated URL

My question here is a little bit unconventional, so it requires a bit of background. I am building a React application and Express server. Firstly, for this application I needed the user to be able to enter their own Google API key and have it saved to the database for future API calls. My front-end React application needs to import the Google API from a script tag, with the user's API key in the query params.

So what I did was I created a route on the server called /api/util/googleAPI which will tell the server to make an AJAX call to get the Google API script using the user's API key and return it. This works all fine and well, I can use a script tag with https://domain/api/util/googleAPI , and it imports the Google API using the user's saved key.

My issue now, is that the create-react-app development server serves on port 3002, but the Express server is on 3001. So in development mode, the request needs to be made cross-origin from port 3002 to port 3001, which requires an absolute URL. But in production, the React application is built and deployed on my Express server, which means now the request needs to be made to 3001, or same-origin. So I want this to work in development, and production without having to change the URL every time. Also, I know it this wouldn't normally be an issue at all if I had a domain name to alias the ports, but this application is made entirely to be served and used on the local network, not online. So I do still need to specify ports.

Right now I am trying to generate the URL like this, but it appears to be loading asynchronously, because the React application begins to run, and errors out because of a missing Google API. However in the inspector I can see the Google API being imported successfully, only just a few moments after the application loads.

<script>
    (function(d, script) {
        script = d.createElement('script');
        script.type = 'text/javascript';
        script.async = false;
        script.src = 'http://' + window.location.hostname + ':3001/api/util/googleAPI';
        d.getElementsByTagName('head')[0].appendChild(script);
    }(document));
</script>

Is there any way to make the inserted script tag load synchronously, or perhaps defer React until the script finishes loading?

To insert a script tag synchronously, the only method is to use document.write('<script src="xxx.js"></script>') .

document.write() will write content into your DOM directly after the script contains it, and then evaluate that the script synchronously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM