document.createElement(“script”) synchronously

前端 未结 11 2075
执念已碎
执念已碎 2020-11-22 12:56

Is it possible to call in a .js file synchronously and then use it immediately afterward?



        
11条回答
  •  囚心锁ツ
    2020-11-22 14:00

    This works for modern 'evergreen' browsers that support async/await and fetch.

    This example is simplified, without error handling, to show the basic principals at work.

    // This is a modern JS dependency fetcher - a "webpack" for the browser
    const addDependentScripts = async function( scriptsToAdd ) {
    
      // Create an empty script element
      const s=document.createElement('script')
    
      // Fetch each script in turn, waiting until the source has arrived
      // before continuing to fetch the next.
      for ( var i = 0; i < scriptsToAdd.length; i++ ) {
        let r = await fetch( scriptsToAdd[i] )
    
        // Here we append the incoming javascript text to our script element.
        s.text += await r.text()
      }
    
      // Finally, add our new script element to the page. It's
      // during this operation that the new bundle of JS code 'goes live'.
      document.querySelector('body').appendChild(s)
    }
    
    // call our browser "webpack" bundler
    addDependentScripts( [
      'https://code.jquery.com/jquery-3.5.1.slim.min.js',
      'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js'
    ] )
    

提交回复
热议问题