javascript - Adding JS File with HTML Code -
is possible create .js file , add html code it. i'm interested in putting client-side scripting coding .js file. can put file in location call upon load html code.
it's on desktop computer no server type of support.
<script type="text/javascript" src="file.js"></script>
i add head section 1 think need. wondered if possible.
thanks!
well, there's few ways of doing you're aiming for.
raw javascript
index.html:
<html> <body> <script src="content.js"></script> </body> </html>
content.js:
document.write('<h1>hello world</h1>');
but should note isn't comfortable large html you're mixing html js.
template engines
a better option template engine, handlebars.js. allows keep html clean , apart javascript. see sample:
index.html:
<html> <body> <script src="handlebars.js"></script> <script src="content.js"></script> </body> </html>
content.js:
var xhr = new xmlhttprequest(); xhr.onload = function() { var template = handlebars.compile(this.responsetext); document.body.innerhtml += template() }; xhr.open('get', 'template.html'); xhr.send();
template.html:
<h1>hello {{name}}</h1>
this won't work on local filesystem, work fine via http.
the biggest benefit of template engine ability fill in dynamic content, instance:
content.js:
var xhr = new xmlhttprequest(); xhr.onload = function() { var template = handlebars.compile(this.responsetext); document.body.innerhtml += template({name: 'world'}) }; xhr.open('get', 'template.html'); xhr.send();
the properties in params of template()
call filled corresponding {{name}}
inside template.
Comments
Post a Comment