Yahoo Answers is shutting down on 4 May 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Linking Javascript files?

Hello,

I am putting together a little website and have come stuck with this:

I am trying to write some Javascript code, in separate files from the web page since the code will be used in several places. One file has the commonly used code with smaller files loaded as and where it is needed alongside this larger common file. This reduces the file sizes quite a bit, no need to load lots of info if not needed.

Anyway, I have 2 files with functions in each. File 1 has say, functionA, file 2 has FunctionB

I want FinctionB to get the output from FunctionA to process it. Easy to do if the functions are both in the same file but these are in separate files - is there a way to link the 2 separate files to that the output of FunctionA can be used by FunctionB (and without having to put FunctionB in the same file as FunctionB since this would make a very large file)

Not interested really in "Don't use that method, use another method" type of answers, just the technical way to call FunctionA within FinctionB

Cheers

1 Answer

Relevance
  • 10 years ago
    Favourite answer

    This should present no problem, provided that functionA has loaded when it is called by functionB. A way to ensure that this is the case, would be to dynamically load the common script from within your smaller script as a sort of dependency, and then set a callback method to fire when the script is loaded.

    For example:

    function loadScript(url, callback){

    var script = document.createElement("script")

    script.type = "text/javascript";

    if (script.readyState){ //IE

    script.onreadystatechange = function(){

    if (script.readyState == "loaded" ||

    script.readyState == "complete"){

    script.onreadystatechange = null;

    callback();

    }

    };

    } else { //Others

    script.onload = function(){

    callback();

    };

    }

    script.src = url;

    document.getElementsByTagName("head")[0].appendChild(script);

    }

    loadScript("functionA.js", function(){

    // call function A after script is loaded

    functionA();

    });

    Note: it appears that the formatting is lost and some of the script is being cut off by Yahoo! Answers. The reader is directed to the citation below for a complete script.

Still have questions? Get answers by asking now.