简体   繁体   中英

Synchronously load and evaluate a dynamically generated script in JavaScript

I'd like to synchronously load and evaluate a script from a third-party. This works fine:

<head>
  <script src="https://unpkg.com/jquery@3.4.1/dist/jquery.js"></script>
  <script type="text/javascript">
    // This prints 'exists' as expected
    console.log(typeof jQuery === "function" ? 'exists' : 'not yet');
  </script>
</head>

But, how would you do this if the src URL is dynamically built and can't be hard-coded? This doesn't work:

<head>
  <script type="text/javascript">
    // Build the URL here
    const src = 'https://unpkg.com/jquery@3.4.1/dist/jquery.js';
    // Create the script tag
    const s = document.createElement('script');
    s.setAttribute('src', src);
    document.head.appendChild(s);
  </script>
  <script type="text/javascript">
    // This prints 'not yet'
    console.log(typeof jQuery === "function" ? 'exists' : 'not yet');
  </script>
</head>

I guess, document.write could do the trick. But, this seems like a bad idea.

What would you recommend?


In my real use case, I need to load the utag.sync.js script:

<script src="https://tags.tiqcdn.com/utag/[account]/[profile]/[env]/utag.sync.js"></script>

env is the dynamic part that is determined based on location.hostname .

Your script load is asynchronous because of the time it takes to download the remote file. So, if you want to know if your script has finished loading, you can attach a "load" event listener on your script element ( s in your example).

 <head> <script type="text/javascript"> // Build the URL here const src = 'https://unpkg.com/jquery@3.4.1/dist/jquery.js'; // Create the script tag const s = document.createElement('script'); s.addEventListener('load', function() { // This prints 'exists' console.log(typeof jQuery === "function"? 'exists': 'not yet'); }); s.setAttribute('src', src); document.head.appendChild(s); </script> <script type="text/javascript"> // This prints 'not yet' console.log(typeof jQuery === "function"? 'exists': 'not yet'); </script> </head>

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