2

I have a metro application in which I want to call a javascript function from another .js file? can anyone help me.

Thank you.

2 Answers 2

5

All scripts in javascript are merged into a "script context". This means that if you have:

File1.js:

function a() { b(); }

File2.js:

function b() { alert("hi"); }

then as long as file2.js is included before b is called, everything will be fine. This means in your HTML should have the <script> tags included, and you'll be good.

If you are using WinJS, a better example might be:

File1.js:

WinJS.Namespace.define("MyNamespace", {
    firstFunction: function() { MyNamespace.secondFunction(); }
});

File2.js

WinJS.Namespace.define("MyNamespace", {
    secondFunction: function() { alert("hi"); }
});

default.html:

<script src="/file1.js"></script>
<script src="/file2.js"></script>

However JavaScript doesn't have a built in dynamic loading of "References". You have to build or use your own.

There are many ways to skin this cat, so I would recommend you look a them and decide which meets your needs.

  • Require JS
  • Built in Page controls/fragment loading in WinJS. If you define a page in WinJS, when the html file for that page is loaded, any scripts declared in the html will be brought in automatically. Same is true of raw fragment loading.
Sign up to request clarification or add additional context in comments.

Comments

0

You can just the file that contains the definition of the function needs to be referenced before the file which calls the function just like you would do if it was a browser not a Windows 8 app.

In fact not even that much is necessary. If you are calling the function after window.load or document.load then that means that all of your referenced javascript files have loaded already so the reference sequence doesn't even matter.

Comments

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.