如何动态加载和使用/调用JavaScript

时间:2016-11-25 15:41:55

标签: javascript

我需要动态加载JavaScript文件,然后访问其内容。

档案test.js

test = function () {
    var pub = {}
    pub.defult_id = 1;
    return pub;
}()


在这种情况下,它有效:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="/test.js"></script>    
</head>
<body>
    <script type="text/javascript">
        console.log(test.defult_id);
    </script>
</body>
</html>


但是我需要动态加载它,这样它就不起作用了:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <script type="text/javascript">
        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);
    </script>
</body>
</html>


错误:Uncaught ReferenceError: test is not defined(…)

3 个答案:

答案 0 :(得分:6)

你可以这样做:

function loadjs(file) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = file;
    script.onload = function(){
        alert("Script is ready!"); 
        console.log(test.defult_id);
    };
    document.body.appendChild(script);
 }

有关详细信息,请阅读以下文章:https://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

答案 1 :(得分:4)

www.html5rocks.com - Deep dive into the murky waters of script loading中,js脚本加载的所有人都有值得一读的好文章。

在考虑了许多可能的解决方案后的那篇文章中,作者得出结论,将js脚本添加到body元素的末尾是避免js脚本阻止页面呈现的最佳方法,从而加快页面加载时间。

但是,作者为那些急需异步加载和执行脚本的人提出了另一个好的替代解决方案。

考虑到您有四个名为script1.js, script2.js, script3.js, script4.js的脚本,您可以使用应用async = false 来执行此操作:

[
  'script1.js',
  'script2.js',
  'script3.js',
  'script4.js'
].forEach(function(src) {
  var script = document.createElement('script');
  script.src = src;
  script.async = false;
  document.head.appendChild(script);
});

现在,规范:一起下载,全部下载后立即执行。

Firefox&lt; 3.6,Opera说:我不知道这个“异步”的东西是什么,但事实上我按照添加的顺序执行通过JS添加的脚本。

Safari 5.0说:我理解“异步”,但不明白用JS将其设置为“false”。我会在他们降落后立即以任何顺序执行你的脚本。

IE&lt; 10说:不知道“异步”,但有一个使用“onreadystatechange”的解决方法。

其他一切都说:我是你的朋友,我们将在本书中做到这一点。

现在,IE的完整代码&lt; 10解决方法:

var scripts = [
  'script1.js',
  'script2.js',
  'script3.js',
  'script4.js'
];
var src;
var script;
var pendingScripts = [];
var firstScript = document.scripts[0];

// Watch scripts load in IE
function stateChange() {
  // Execute as many scripts in order as we can
  var pendingScript;
  while (pendingScripts[0] && pendingScripts[0].readyState == 'loaded') {
    pendingScript = pendingScripts.shift();
    // avoid future loading events from this script (eg, if src changes)
    pendingScript.onreadystatechange = null;
    // can't just appendChild, old IE bug if element isn't closed
    firstScript.parentNode.insertBefore(pendingScript, firstScript);
  }
}

// loop through our script urls
while (src = scripts.shift()) {
  if ('async' in firstScript) { // modern browsers
    script = document.createElement('script');
    script.async = false;
    script.src = src;
    document.head.appendChild(script);
  }
  else if (firstScript.readyState) { // IE<10
    // create a script and add it to our todo pile
    script = document.createElement('script');
    pendingScripts.push(script);
    // listen for state changes
    script.onreadystatechange = stateChange;
    // must set src AFTER adding onreadystatechange listener
    // else we’ll miss the loaded event for cached scripts
    script.src = src;
  }
  else { // fall back to defer
    document.write('<script src="' + src + '" defer></'+'script>');
  }
}

稍后一些技巧和缩小,它是362字节

!function(e,t,r){function n(){for(;d[0]&&"loaded"==d[0][f];)c=d.shift(),c[o]=!i.parentNode.insertBefore(c,i)}for(var s,a,c,d=[],i=e.scripts[0],o="onreadystatechange",f="readyState";s=r.shift();)a=e.createElement(t),"async"in i?(a.async=!1,e.head.appendChild(a)):i[f]?(d.push(a),a[o]=n):e.write("<"+t+' src="'+s+'" defer></'+t+">"),a.src=s}(document,"script",[
  "//other-domain.com/1.js",
  "2.js"
])

答案 2 :(得分:1)

Dinamically加载JS文件是异步的,所以为了确保在调用内部函数之前加载脚本,请在脚本中使用onload事件:

body {
  margin: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
}
main {
  flex: 3;
  background-color: purple;
  fill: purple;  /* Color svg separator will inherit from */
  position: relative;
}
svg {
  width: 100%;
  height: 50px;
  position: absolute;
  top: 100%;
  fill: inherit;
}
footer {
  flex: 1;
  padding-top: 50px;  /* svg separator height */
  background-color: gold;
}