1

If I know that when a certain condition is true, I'll need to run different scripts, is it possible to load the script dynamically into a function I'm running?

$("#container").on("click", "#submit", function(){
    var prodID = $("#productSelect").find(".selected_option").data("product_id");

    //somehow load a script like "validation_" + prodId;

});

Or should I manually put all the code into a single function

$("#container").on("click", "#submit", function(){
    var prodID = $("#productSelect").find(".selected_option").data("product_id");

    switch (prodID){
       case 1:
       //code for prodID 1
       break;

       case 2:
       //code for prodID 2
       break;

       case 3:
       //code for prodID 3
       break;

    }

});

It is just an attempt to keep things a little cleaner looking. I don't know if it's a good idea. Thanks.

2
  • $.getScript() ? Commented Feb 28, 2013 at 17:41
  • have you considered requirejs? Commented Feb 28, 2013 at 17:42

1 Answer 1

1

i'd recommend to go with

$("#container").on("click", "#submit", function(){
  var prodID = $("#productSelect").find(".selected_option").data("product_id");

  switch (prodID){
   case 1:
   functionForCase1();
   break;

   case 2:
   functionForCase2();
   break;

   case 3:
   functionForCase3();
   break;

  }
});

function functionForCase1(){
   //code for prodID 1
}

function functionForCase2(){
   //code for prodID 2
}

function functionForCase1(){
   //code for prodID 3
}
Sign up to request clarification or add additional context in comments.

1 Comment

I see. I think I will go with this idea, yes. Seems better to keep everything in one file anyway. Good point. Thank you.

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.