简体   繁体   中英

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

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>");
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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