To paraphrase Ian Malcolm, it is not so much whether you can do it.
There are two ways to execute the code that came from the server, and usually it depends on where the code is from.
Javascript has a function called eval() that takes a string and executes it as Javascript. The main problem is that you cannot be sure what this string contains. In the world of Internet security, most people will argue that you can never be sure of the incoming data, and therefore you should never use eval for incoming data.
Another JSONP method. This method allows you to retrieve data from remote sources. It does this by creating a <SCRIPT> tag that pulls out remote Javascript. Your JSONP source call usually includes a callback function that is called when JSONP data is received, giving your local code access to it.
Not knowing exactly what you want to achieve, I do not want to make any assumptions, but let me make some suggestions.
Calling code on demand from the server can be a bit heavy. I cannot think of many scripts (read-any), in which the best approach would be to call special functions from the server. However, I can imagine a scenario in which you have a large set of potential functions that you can perform, and you do not want to download them to the browser at the same time. I would suggest two approaches:
- Perform functions on the server. Just send the data to the server in some format and return the result. Leave the processing on the server
- If you need a function that is currently not available in the browser, download the script file containing this function, then call the function in your Javascript. Think of these files as dynamically loaded libraries that you call when and when you need them. You are limited to your own server using this method, which improves security (if you believe that your own server will not send malicious code.
In short, I would say that a design that requires you to immediately take text from the server and execute it as code can indicate a problem in this project. But you did not come here to review the design, so I hope these suggestions help you find a good approach.
source share