SitePoint Sponsor

User Tag List

Results 1 to 21 of 21

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Nov 2009
    Posts
    311
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Dynamically loading JS script

    Hi,

    I am getting a parameter from the URL and based on that parameter, I want to load a different JS file. I tried everything I found on the web but I couldn't make it work.

    Here is my code:

    HTML Code:
    // This line gets the parameter from the URL i.e. mypage.html?var=var1.
    <script>var myVar = location.search.split('var=')[1];</script>
    
    // This line is supposed to load the javascript file based on var parameter. If var is var1, it will load var1.js, if var is var2, it will load var2.js etc.
    <script src="scripts/var1.js"></script>
    I have both lines within <head> element. I need this to work locally, not on a server. I can't use Ajax type of solution (I guess). For example, I tried the first 3 solutions on this page but they didn't work for me.

  2. #2
    SitePoint Enthusiast bronze trophy \\.\'s Avatar
    Join Date
    Oct 2013
    Location
    UK
    Posts
    72
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    This is what you need

    Code:
    myVar= location.search.split("var=").pop();
    var addScript = document.createElement("script");
    addScript.type = "text/javascript";
    addScript.src = myVar;
    (document.getElementsByTagName("head")[0] || document.documentElement ).appendChild(addScript);

  3. #3
    SitePoint Addict
    Join Date
    Nov 2009
    Posts
    311
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by \\.\ View Post
    This is what you need

    Code:
    myVar= location.search.split("var=").pop();
    var addScript = document.createElement("script");
    addScript.type = "text/javascript";
    addScript.src = myVar;
    (document.getElementsByTagName("head")[0] || document.documentElement ).appendChild(addScript);
    Thank you but it is not working for me. I am testing this by displaying a variable from var1.js on the main page but it is not displayed. Where do I put this code? Maybe the issue is something about page/script loading etc.?

    Here is my whole setup with your code:

    var1.js
    HTML Code:
    var myVar = 'Test';
    page2.html (you land on page2.html when you click "page1.html?var=var1")
    HTML Code:
    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="utf-8" />
    	<title>Page Title</title>
    	<script>
    	var getVar= location.search.split('var=')[1];
    	var addScript = document.createElement('script');
    	addScript.src = getVar + '.js';
    	(document.getElementsByTagName('head')[0] || document.documentElement ).appendChild(addScript);
    	</script>
    </head>
    <body>
    	<script>alert(myVar);</script>
    </body>
    </html>

  4. #4
    SitePoint Enthusiast bronze trophy \\.\'s Avatar
    Join Date
    Oct 2013
    Location
    UK
    Posts
    72
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    In order to display a value in an alert, your script mush have run in order for it to produce a variable that has a value and can be displayed.

    Something like this (untested and likely not working) would be the right direction to go in

    Code:
    displayIt = {
        init:function(){
            if( myVar ){
                clearInterval(auto);
                this.showMe();
            }
        },
        showMe:function(){
                alert( myVar );
        },
        auto:setInterval("displayIt.init()",2000)
    }
    What is meant to happen is the displayIt.init() function is called every 2 seconds until the variable is available to display, when it exists then the interval is cleared and then the displayIt.showMe() function is called and the alert causes the value of the JavaScript to show.

  5. #5
    SitePoint Enthusiast bronze trophy \\.\'s Avatar
    Join Date
    Oct 2013
    Location
    UK
    Posts
    72
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Also... why did you remove the
    Code:
    addScript.type = "text/javascript";
    from your implementation?

  6. #6
    SitePoint Addict
    Join Date
    Nov 2009
    Posts
    311
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by \\.\ View Post
    Also... why did you remove the
    Code:
    addScript.type = "text/javascript";
    from your implementation?
    Hi,

    Isn't there a way to just check if the script is fully loaded such as jquery's ready feature? My purpose is not to display something with alert, I am using it to test if my code is working. I just want to use the code/variables in var1.js on my page when the page is loaded. I removed the above part because it is not necessary as far as I know. Thanks for your help.

  7. #7
    SitePoint Enthusiast bronze trophy \\.\'s Avatar
    Join Date
    Oct 2013
    Location
    UK
    Posts
    72
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    You can test if the variable is ready through a routine a bit like I proposed which will be very similar to JQuery, however I personally don't use JQuery, IMHO it is a completely wasteful resource given that you are suggesting that you want to load a few hundred lines of code to test if a variable is ready.

    JavaScript (Which JQuery iw written in) uses the typeOf function to see if a variable is undefined or not.

    I prefer KISS (Keep It Simple Stupid) philosophy here.

  8. #8
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,861
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    The simplest way to tell if a given script has loaded is to add a line at the end of that script that sets a variable with a value to indicate that it is loaded.

    Better is to put all the JavaScript that is interdependent inside the one script so that other scripts don't care whether that one has loaded or not as each is entirely self contained.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  9. #9
    SitePoint Addict
    Join Date
    Nov 2009
    Posts
    311
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by \\.\ View Post
    You can test if the variable is ready through a routine a bit like I proposed which will be very similar to JQuery, however I personally don't use JQuery, IMHO it is a completely wasteful resource given that you are suggesting that you want to load a few hundred lines of code to test if a variable is ready.

    JavaScript (Which JQuery iw written in) uses the typeOf function to see if a variable is undefined or not.

    I prefer KISS (Keep It Simple Stupid) philosophy here.
    Thanks for all your help. I am not using jQuery just to test a variable, I'm using it for a lot of other things. I just want to dynamically load a javascript file and use the code/variables in it.

  10. #10
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,861
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by nayen View Post
    I am not using jQuery just to test a variable
    You could use the same JavaScript that jQuery uses yourself without using jQuery.

    jQuery itself is written in JavaScript and so everything that jQuery can do has at least one native JavaScript equivalent.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  11. #11
    SitePoint Addict
    Join Date
    Nov 2009
    Posts
    311
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by felgall View Post
    The simplest way to tell if a given script has loaded is to add a line at the end of that script that sets a variable with a value to indicate that it is loaded.

    Better is to put all the JavaScript that is interdependent inside the one script so that other scripts don't care whether that one has loaded or not as each is entirely self contained.
    I want to use the code/variables contained in the dynamically loaded script in my main page, that's my purpose.

  12. #12
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,880
    Mentioned
    74 Post(s)
    Tagged
    6 Thread(s)
    Off Topic:

    If and only if the page was PHP and not HTML it would be a lot simpler:

    Code:
    <?php
    
    /* 
      This line gets the parameter from the URL i.e. mypage.html?var=var1.
      This line is supposed to load the javascript file based on var parameter. 
      If var is var1, it will load var1.js, if var is var2, it will load var2.js etc.
    */
    
    $jsFile = isset($_GET['var']) ? $_GET['var'] : 'jsDefault';
    
    echo '<script src="scripts/' .$jsFile .'.js" type="text/javascript"></script>';
    
    ?>

    Last edited by John_Betong; Mar 16, 2014 at 00:26. Reason: added missing .js extension
    Learn how to be ready for The New Move to Discourse

    How to make Make Money Now with a *NEW* look

    Be sure to congratulate Wolfshade on earning Member of the Month for August 2014

  13. #13
    SitePoint Addict
    Join Date
    Nov 2009
    Posts
    311
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by John_Betong View Post
    Off Topic:

    If and only if the page was PHP and not HTML it would be a lot simpler:

    Code:
    /* 
      This line gets the parameter from the URL i.e. mypage.html?var=var1.
      This line is supposed to load the javascript file based on var parameter. 
      If var is var1, it will load var1.js, if var is var2, it will load var2.js etc.
    */
    
    
    $jsFile = isset($_GET['var']) ? $_GET['var'] : 'jsDefault';
    echo '<script src="scripts/' .$jsFile .'.js"></script>';
    ?>

    Yeah, thank you. I know how to do it in PHP I just need in JS.

  14. #14
    SitePoint Addict
    Join Date
    Nov 2009
    Posts
    311
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I finally found the solution and I am posting here in case someone else needs to dynamically load JS files. I have no idea why it didn't work before when I tested.

    var1.js
    HTML Code:
    var myVar = 'Test';
    page2.html (you land on page2.html when you click "page1.html?var=var1")
    HTML Code:
    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="utf-8" />
    	<title>Page Title</title>
    	<script>
    	var getVar= location.search.split('var=')[1];
    	document.write('<script src="' + getVar + '.js"><\/script>'); // Don't forget to escape the forward slash in closing script tag.
    	</script>
    </head>
    <body>
    	<script>document.write(myVar);</script> // For testing if it works.
    </body>
    </html>
    Thank you all once again for your input.

  15. #15
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,311
    Mentioned
    19 Post(s)
    Tagged
    1 Thread(s)
    Since the OP is already using jQuery for other things, it seems silly to avoid it.

    @nayen Another option you could use:

    Code JavaScript:
    $.getScript( getVar + ".js", function( data, textStatus, jqxhr ) {
      console.log( data ); // Data returned
      console.log( textStatus ); // Success
      console.log( jqxhr.status ); // 200
      console.log( "Load was performed." );
     
      alert(myVar);
    });
    "First make it work. Then make it better."

  16. #16
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,996
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by Jeff Mott View Post
    Since the OP is already using jQuery for other things, it seems silly to avoid it.
    I don't think the OP is using jQuery.

    Actually, scrub that. Reading through the thread, it seems that he is.
    Sorry for the noise.

  17. #17
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,311
    Mentioned
    19 Post(s)
    Tagged
    1 Thread(s)
    This line left me with the impression that he is.

    Quote Originally Posted by nayen View Post
    Thanks for all your help. I am not using jQuery just to test a variable, I'm using it for a lot of other things. I just want to dynamically load a javascript file and use the code/variables in it.
    "First make it work. Then make it better."

  18. #18
    SitePoint Enthusiast bronze trophy \\.\'s Avatar
    Join Date
    Oct 2013
    Location
    UK
    Posts
    72
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    JQuery has a way of loading scripts dynamically, so why not use that instead of asking a JavaScript question?
    https://api.jquery.com/jQuery.getScript/

  19. #19
    SitePoint Addict
    Join Date
    Nov 2009
    Posts
    311
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by \\.\ View Post
    JQuery has a way of loading scripts dynamically, so why not use that instead of asking a JavaScript question?
    https://api.jquery.com/jQuery.getScript/
    I have my solution working now but thanks for the suggestion. Does that work locally (not on a server)?

  20. #20
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,996
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Depends which browser.
    It won't work locally on Chrome.

  21. #21
    SitePoint Enthusiast bronze trophy \\.\'s Avatar
    Join Date
    Oct 2013
    Location
    UK
    Posts
    72
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    You should get a copy of JQuery and a web server (development) environment, for example XAMPP.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •