简体   繁体   English

页面加载前如何动态包含JavaScript文件

[英]How to dynamically include a javascript file, before the page loads

I want to include a local .js file in my index.html page, based on the outcome of an 'if' statement, as described in my sample code below. 我想根据'if'语句的结果在我的index.html页面中包含一个本地.js文件,如下面的示例代码中所述。 I need the .js contents to be included in the initial loading of the page, as the contents will be displayed in the html itself on load. 我需要将.js内容包含在页面的初始加载中,因为内容将在加载时显示在html本身中。

index.html: index.html的:

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

script.js: 的script.js:

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

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

Try this instead 试试这个

<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>

If you need the script to be loaded before the document loads, you'll need to include the conditional script in the head section of the document. 如果需要在加载文档之前先加载脚本,则需要在文档的head部分添加条件脚本。

You can do something like this: 您可以执行以下操作:

<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>

Note that your function declaration is wrong: 请注意您的函数声明是错误的:

include_another_script function() {

尝试此操作,src是要加载的脚本的路径。
var script = document.createElement('script');
script.src = src;
document.head.appendChild(script);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM