title: How to dynamically load and use/call a JavaScript file?
body: <p>I need to dynamically load a JavaScript file and then access its content.</p>
  
  <p>File <code>test.js</code></p>
  
  <pre><code>test = function () {
      var pub = {}
      pub.defult_id = 1;
      return pub;
  }()
  </code></pre>
  
  <p><br />
  In this case it works:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;script type="text/javascript" src="/test.js"&gt;&lt;/script&gt;    
  &lt;/head&gt;
  &lt;body&gt;
      &lt;script type="text/javascript"&gt;
          console.log(test.defult_id);
      &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><br />
  But I need to load it dynamically, and that way it does not work:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;script type="text/javascript"&gt;
          function loadjs(file) {
              var script = document.createElement("script");
              script.type = "application/javascript";
              script.src = file;
              document.body.appendChild(script);
          }
          loadjs('test.js');
          console.log(test.defult_id);
      &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><br />
  Error: <code>Uncaught ReferenceError: test is not defined(…)</code></p>