Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Externalising JavaScript

  • 03-06-2010 7:54pm
    #1
    Registered Users, Registered Users 2 Posts: 3,849 ✭✭✭


    Hey everyone. (noob warning!)

    I have some javascript on a page which I am trying to move to an external js file, rather than be embedded.

    My understanding was that the javascript simply had to be placed into a text file and named whatever.js

    I've tried a few times but not had any success.

    Perhaps someone could point me in the right direction.

    ________________________________


    I've made a simplistic version of my code here, which basically matches vowels and consonants to make a pseudo word.

    <p>
        
        <script type="text/javascript">
    function createRan(length) {
        var type1 = 'bcdfg',
            type2 = 'aaaaa',
            rand = function(limit) {
                return Math.floor(Math.random()*limit);
            },
            i, word='', length = parseInt(length,10),
            type1 = type1.split(''),
            type2 = type2.split('');
        for (i=0;i<length/2;i++) {
            var ran1 = type1[rand(type1.length)],
                ran2 = type2[rand(type2.length)];
            word += (i===0) ? ran1.toUpperCase() : ran1;
            word += i*2<length-1 ? ran2 : '';
        }
        return word;
    }
    document.write( createRan(6) );
    
    </script>
    
    <input type="button" value="RELOAD" onClick="window.location.reload()">
    
        </p>
    

    When I put the js into an external file, it doesn't seem to execute automatically.

    Thanks for any help here. I'm tearing my hair out.


Comments

  • Registered Users, Registered Users 2 Posts: 35,524 ✭✭✭✭Gordon


    Are you putting the html into the js file also?!

    Have a look at the source of this page and do a text search for sorttable and you'll find an example of an external javascript file and how it plugs in to the page. Also, you need to call the function/javascript within the html afaiu, but maybe your post above is just an example?


  • Registered Users, Registered Users 2 Posts: 3,849 ✭✭✭condra


    Hi. Thanks for your reply!

    No, I'm only putting the javascript in the JS file, and linking to it from the script tag in the HTML/BODY.

    I'm thinking the document.write bit is the problem, that perhaps that needs to be somehow part of the HTML code, or indeed the function "called up" in HTML.

    I've debugged it and it appears to have no problems. Its like its reading the javascript but not displaying the result on the page.

    By the way, it does work when embedded.


  • Closed Accounts Posts: 18,163 ✭✭✭✭Liam Byrne


    I'd recommend "externalising" everything in the function, but leaving the document.write within the document itself, as a single script call.


  • Users Awaiting Email Confirmation Posts: 351 ✭✭ron_darrell


    Have to agree with the above poster. Externalised javascript has to be called or it will never execute (by that I mean you have to call the function in order for it to run - simply adding an external javascript file to a page won't make the javascript in that file run) but I also have to ask, are you sure you have added the external file properly?
    <script src="path_to_external_file/filename.js" type="text/javascript"></script>
    

    Hope that helps,
    Regards,
    RD


  • Closed Accounts Posts: 18,163 ✭✭✭✭Liam Byrne


    Externalised javascript has to be called or it will never execute (by that I mean you have to call the function in order for it to run

    To be fair to the OP, they have done this:

    document.write(createRan(6))


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 3,849 ✭✭✭condra


    Thanks for all the help guys.

    I think I'm getting closer, though I'm not sure where to go from here.

    I tried putting the document.write as a seperate script call.. I think.

    My HTML code now looks like this:
    <p>
    <script type="text/javascript" src="go.js"></script>
    
    <script type="text/javascript">
    document.write( createRan(6) );
    document.write("</P>");
    </script>
    
    
    <input type="button" value="RELOAD" onClick="window.location.reload()">
    
        </p>
    

    and the js file:
    function createRan(length) {
        var type1 = 'bcdfg',
            type2 = 'aaaaa',
            rand = function(limit) {
                return Math.floor(Math.random()*limit);
            },
            i, word='', length = parseInt(length,10),
            type1 = type1.split(''),
            type2 = type2.split('');
        for (i=0;i<length/2;i++) {
            var ran1 = type1[rand(type1.length)],
                ran2 = type2[rand(type2.length)];
            word += (i===0) ? ran1.toUpperCase() : ran1;
            word += i*2<length-1 ? ran2 : '';
        }
        return word;
    }
    

    It's still not working. Perhaps I need to run the whole CreateRan function from the HTML?

    Sorry for being so braindead. Javascript is a bit of a blindspot for me.


  • Closed Accounts Posts: 18,163 ✭✭✭✭Liam Byrne


    Firstly, don't have the document.write("</p>")

    Secondly, is there a chance that you're using MS Windows, with the file extensions hidden ?

    Because if so, then the file that looks like "go.js" could actually be called "go.js.txt"

    The following works for me :

    go.js
    function createRan(length) {
        var type1 = 'bcdfg',
            type2 = 'aaaaa',
            rand = function(limit) {
                return Math.floor(Math.random()*limit);
            },
            i, word='', length = parseInt(length,10),
            type1 = type1.split(''),
            type2 = type2.split('');
        for (i=0;i<length/2;i++) {
            var ran1 = type1[rand(type1.length)],
                ran2 = type2[rand(type2.length)];
            word += (i===0) ? ran1.toUpperCase() : ran1;
            word += i*2<length-1 ? ran2 : '';
        }
        return word;
    }
    

    test.html
    <script type="text/javascript" src="go.js"></script>
    <p><script type="text/javascript">
    document.write( createRan(6) );
    </script>
    </p>
    


  • Registered Users, Registered Users 2 Posts: 3,849 ✭✭✭condra


    Cheers Liam. I used your example and that works.

    I have a lot of bits of code and files for my main page, so skrew it, I'll build it up from the files I made with your code here.

    Thanks a million Liam and everyone else.


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    The following works for me:-
    function createRan(length) {
        var type1 = 'bcdfg',
            type2 = 'aaaaa',
            rand = function(limit) {
                return Math.floor(Math.random()*limit);
            },
            i, word='', length = parseInt(length,10),
            type1 = type1.split(''),
            type2 = type2.split('');
        for (i=0;i<length/2;i++) {
            var ran1 = type1[rand(type1.length)],
                ran2 = type2[rand(type2.length)];
            word += (i===0) ? ran1.toUpperCase() : ran1;
            word += i*2<length-1 ? ran2 : '';
        }
        return word;
    }
    
    document.write(createRan(6));
    

    test.html
    <p>
    <script type="text/javascript" src="go.js"></script>
    </p>
    

    Some things to note.

    If you aim to produce xhtml web pages be aware that document.write is invalid in xhtml. Yes it will work in modern (overly forgiving) browsers at the moment but if you want to be future proof..

    The document.write(createRan(6)); part placed in the external file means it will attempt to run as soon as the browser parses the document. With the link to the external file in the place where you want the html to be written it should work fine but this is all round very bad practice.

    An example of how I would actually do something like this:-
    window.onload = function()   {
       var randomPara = document.getElementById("randomtext");
       if (randomPara)   {
          randomPara.appendChild(document.createTextNode(createRan(6)));
       }
    };
    
    function createRan(length) {
        var type1 = 'bcdfg',
            type2 = 'aaaaa',
            rand = function(limit) {
                return Math.floor(Math.random()*limit);
            },
            i, word='', length = parseInt(length,10),
            type1 = type1.split(''),
            type2 = type2.split('');
        for (i=0;i<length/2;i++) {
            var ran1 = type1[rand(type1.length)],
                ran2 = type2[rand(type2.length)];
            word += (i===0) ? ran1.toUpperCase() : ran1;
            word += i*2<length-1 ? ran2 : '';
        }
        return word;
    }
    
    
    <html>
    <head>
    <script type="text/javascript" src="go.js"></script>
    </head>
    <body>
    <p id="randomtext"></p>
    </body>
    </html>
    

    The one down side here is that the window.onload event could be overwritten by other script you put on your page or you could be overwriting another script yourself so other stuff breaks. Things like jQuery make it easier to work nicely with other script:-
    $(document).ready(function()   {
       $("#randomtext").html(createRan(6));
    });
    

    $(document).ready allows you to add functions to be run when the document is ready (page loaded) and does not remove any other functions that may be set to that event too. It's not a requirement to use jquery but this is just an example.


Advertisement