0

I want to know if there is a way to conditionally include a script file inside of <script></script> tags.

I'm trying to do something like this:

<script>
if(condition)
{
    <script src="/hts/functions.js"></script> //include this file if condition is met
}
</script>

I found this code:

$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );
});

However, I don't understand how to use it.

Is there a way to do this?

2
  • Are you using jQuery? Commented Jul 21, 2014 at 14:24
  • There is if that if has something to do with Internet Explorer, then you could use conditional statements, otherwise, you could just "borrow" the async loading code that Google, facebook etc. uses for scripts, and place it in the condition. Commented Jul 21, 2014 at 14:25

2 Answers 2

1

You're on the right track with $.getScript:

if(someConditionIsTrue){
    // load script from the server
    $.getScript( "somePath/onTheServer/script.js", function( data, textStatus, jqxhr ) {
        // do something after the load is complete
    });
}
Sign up to request clarification or add additional context in comments.

Comments

1

To use the script, add the code in the .getScript callback to your JavaScript for the page. Any code that depends on the script you are injecting should be included or called from inside the .getScript callback.

In the code you pasted, the console.log statements run after the injected script loads. Here's an example of using $.getScript to load the Underscore.js library and log the version of Underscore to the console:

var condition=true;
var pathToScript='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js';
if(condition){
    // load script from the server
    $.getScript( pathToScript, function( data, textStatus, jqxhr ) {
        console.log(_.VERSION);
    });
};

JSFiddle: http://jsfiddle.net/WA4f4/2/

I slightly modified your code so it would work in JSFiddle and to demonstrate that the code inside the callback to getScript can access variables from the injected script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.