如何在页面加载之前动态包含javascript文件

时间:2014-02-11 19:49:34

标签: javascript jquery html

我希望在我的index.html页面中包含一个本地.js文件,基于'if'语句的结果,如下面的示例代码所述。我需要将.js内容包含在页面的初始加载中,因为内容将在加载时显示在html中。

的index.html:

<html>
  <head>
     <script src="script.js"></script>
  </head>
<body>
     <script>
         include_another_script();
     </script>
</body>
</html>

的script.js:

include_another_script function(){
    var url;
    if( //some stuff){
        url = "script1.js";
    } else {
        url = "script2.js";
    }

    document.write("<script src=url></script>");
}

3 个答案:

答案 0 :(得分:1)

试试这个

<head>
<script type="text/javascript">

var url;
if( blah == blah){
url = 'myUrl.js';
}else{
url = 'myOtherUrl.js';
}

var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = url;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);

</script>
</head>

答案 1 :(得分:0)

如果您需要在加载文档之前加载脚本,则需要在文档的head部分中包含条件脚本。

您可以这样做:

<head>
    <script src="script.js"></script>
    <script type="text/javascript">
        function include_another_script(){
            var url;
            if( //some stuff){
                url = "script1.js";
            } else {
                url = "script2.js";
            }
            $('head').append('<script type="text/javascript" src="'+url+'"></script>');
        }
   </script>
</head>

请注意,您的函数声明错误:

include_another_script function() {

答案 2 :(得分:0)

试试这个,src是你要加载的脚本的路径     var script = document.createElement('script');
script.src = src;
document.head.appendChild(script);