简体   繁体   中英

call a function in a javascript file not included in page

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

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM