2

Here is an example:

I have a file 1.js, which has some functions. I have to make them available to another file 2.js. 1.js is not included in the page, but 2.js is (using src='').

Is there a way to do this? I do not want to expose 1.js at all to the users, but want to use its functions in 2.js

2 Answers 2

5

Description

JavaScript works on the client (Browser) so you have to make the file available to them. Consider to encode and minify the file to make it harder to read.

More Information

Online Javascript Compression Tool

JavaScript Compressor - Compress JavaScript Code Online for Free

HTML/text/JavaSript Escaping/Encoding Script

Free Javascript Obfuscator - Protects JavaScript code from stealing and shrinks size

Update

  1. You can do a Ajax call to get the javascript and use eval. I would do it this way using jQuery .load().

  2. It is possible to include a javascript-file using javascript like this

    function include(filename)
    {
        var head = document.getElementsByTagName('head')[0];
    
        script = document.createElement('script');
        script.src = filename;
        script.type = 'text/javascript';
    
        head.appendChild(script)
    

    }

Then you can call methods from the other script / source. But this is visible to the user and experienced users will find this. Its harder to find as a simple

<script src="..." type="text/javascript"></script>
Sign up to request clarification or add additional context in comments.

3 Comments

one more query: if we simply include that 1.js in 2.js, will it serve the purpose? I mean, if we only include 2.js only on the page?
No. not merging. on top of 2.js, if we use ///src='1.js', we can see the methods in auto-complete of our editor. Does it mean that have 'included' 1.js or its there just to provide access to the functions in 1.js
No, you cant use the script tag in a javascript file, because the script tag is html. But you can use the include method from my answer in your 2.js to load 1.js
3

You are not able to keep javascript private. If you want it to run, the user would be able to see it. You can obfuscate it but even these methods can be broken so if this is about privacy try another method. You can organize it using closures into sort of classes and objects but even these can be called by a determined user.

2 Comments

i was asked this question in an interview. i said what you have suggested, but the guy did not seem to be convinced with it :(
There are many things you can do to hide it but since it must run on the user's machine they ultimately will have complete control over it.

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.