简体   繁体   中英

Safe way to include javascript file dynamically

I have a lang folder which contains the language variables for a website. Depending on the button clicked by the user, I want to include the desired file. So if the user chooses the english language, a session variable stores lang = 'en'. Then the file ./lang/en/client_vars.js in included so that I can call these variables. If the user chooses the chinese language, 'ch' is stored in the session and the file to include is ./lang/ch/client_vars.js. Till now this is what I have thought:

  1. <script type="text/javascript" src="set_language.js"></script> is included in the head section.
  2. inside the set_language.js file, I get the session variable value like this:

     var language; $.ajaxSetup({cache: false}) $.get('get_session.php', function (data) { language = data; }); 

    The get_session file was the file where the language session variable was declared and set.

  3. Third step is to include the desired js file. This is where i am stuck. In a normal situation, if there was only one possible file, I would have done it in the head section as

     <script type="text/javascript" src="./lang/en/client_vars.js"></script> 

But since I need to get that variable with ajax first, I don't know how to deal with it.

Try:

$.get('get_session.php', function (data) {
    language = data;
    $.getScript('./lang/' + language + '/client_vars.js');
});

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