p1xelarchitect
p1xelarchitect

Reputation: 289

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

Upvotes: 0

Views: 1097

Answers (3)

ojovirtual
ojovirtual

Reputation: 3362

Try this, src is the path to the script you want to load.
var script = document.createElement('script');
script.src = src;
document.head.appendChild(script);

Upvotes: 0

Alex W
Alex W

Reputation: 38253

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() {

Upvotes: 0

VIDesignz
VIDesignz

Reputation: 4783

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>

Upvotes: 1

Related Questions