简体   繁体   中英

How to embed javascript code dynamically into HTML

We have a requirement, where a javascript needs to be rendered dynamically when the HTML page is rendered. The javascript function could be used to draw a circle or triangle or a square. Assuming the following code snippet is stored in a certain field in the database, how do you embed such code directly into HTML at a certain location.

<script src="../js/processing.js"></script>
<script src="../js/shapes.js"></script>

<div style="clear:both;"/>
<canvas id="canvas1" width="200" height="200"></canvas>

<script id="script1" type="text/javascript">
var sketch = new Processing.Sketch();
sketch.attachFunction = function(processing) {
processing.setup = setup(processing);
processing.draw = drawCircle(processing);
};

var canvas = document.getElementById("canvas1");
var p = new Processing(canvas, sketch);
</script>

This is quite easy using AJAX. Obtain the script snippet using AJAX and then place it in a script tag in your body, it should execute :).

Yes, this can easily be done but way is vary as per server technology.

like in Ruby on Rails:

let assume your script is stored in some ruby variable say js_script as

 js_script = 'var sketch = new Processing.Sketch();
 sketch.attachFunction = function(processing) {
 processing.setup = setup(processing);
 processing.draw = drawCircle(processing);
};

var canvas = document.getElementById("canvas1");
var p = new Processing(canvas, sketch);'

Following code will work in your HTML file

<script id="script1" type="text/javascript">


<%= js_script -%> #  here the magic happens, it replaced this block with js_script 


</script>

Note:In order to execute dynamic script properly, you should load all required elements and js files before calling it.

Like in your case you should call it after creating canvas1 element because it is required in your script

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