How to handle common code in multiple HTML's using javascript or jQuery -
i have application has 30 html's , share common code f made changes need change on every page. below piece of code using on pages.
<div> <ul> <li class="current"><a href=".html" ></a></li> <li><a href=".html"></a></li> <li><a href=".html"></a></li> <li><a href=".html"></a></li> </ul> </div>
is there solution can keep on single file , reuse ever want?
there several ways can achieve inclusion keep code more maintainable.
php
of course first comes mind if want use php usage of include()
includes , evaluates code in external file or script.
you can use such:
<?php include('path/to/file.html'); ?>
note! careful: container file must .php
file in order directive evaluated server. don't need changing file extension, happen. and, of course, make sure server can parse php.
also, beware of difference include_once()
, not recommend in case.
ssi (server side include)
if don't want use php, can simple , clean server side include[wikipedia]. ssi looks html comment:
<!--#include virtual="your.html" -->
note! have make sure have mod_include
installed , enabled in apache server, , add following directive either in httpd.conf
or .htaccess
file:
options +includes
read doc link above more information.
client-side includes
your question specifies in js or jquery. not sure if because not aware of server-side options, or if wanted client-side one. in case, there client-side solutions.
given possibility, i recommend server-side solutions problem.
iframe element
the <iframe>
element includes content external file in separate area in page. can use so:
<iframe src="your.html" width="x" height="y"><p>fallback text</p></iframe>
object element
the <object>
element similar thing <iframe>
, while latter designed more means sandbox application, former feels more integrated in page. usage follows:
<object type="text/html" data="your.html"></object>
javascript insertion
convert code javascript file , instruct file insert content dom. here example
external.js
var element = '<div> <ul> <li class="current"><a href=".html" ></a></li> <li><a href=".html"></a></li> <li><a href=".html"></a></li> <li><a href=".html"></a></li> </ul> </div>';
container.html
<script type="text/javascript" src="external.js"></script> <script> document.getelementbyid('#containing-element').innerhtml(element); </script>
ajax
jquery can deal ajax calls easily. use jquery.get()
or jquery.load()
. suggest use latter, load()
injects loaded element directly dom, , can specify part load, nifty if store includes in 1 external html file.
jquery(document).ready(function ($){ $('#containing-element').load('your.html'); });
Comments
Post a Comment