How to handle common code in multiple HTML's using javascript or jQuery

后端 未结 4 2105
长情又很酷
长情又很酷 2021-02-13 17:40

I have an application which has almost 30 html\'s and they share some common code to which i f i made any changes i need to change it on every page. Below is the piece of code w

4条回答
  •  灰色年华
    2021-02-13 18:09

    There are several ways you can achieve this inclusion to keep your code more maintainable.

    PHP


    Of course the first that comes to mind is if you want to use PHP is the usage of include() which includes and evaluates the code in your external file or script.

    You can use it as such:

    
    

    Note! Be careful: your container file must be a .php file in order for this directive to be evaluated from the server. You don't need to do anything but changing the file extension, for that to happen. And, of course, make sure that your server can parse PHP.

    Also, beware of the difference with include_once(), which I would not recommend in this case.

    SSI (Server side include)


    If you don't want to use PHP, you can do that very simple and clean with a Server side include[Wikipedia]. An SSI looks like an HTML comment:

    
    

    Note! You will have to make sure to have mod_include installed and enabled in your Apache server, and to add the following directive either in your httpd.conf or .htaccess file:

    Options +Includes
    

    Read the doc link above for more information.

    Client-side includes


    Your question actually specifies to do this in JS or jQuery. Not sure if it does because you were not aware of the server-side options, or if you really wanted a client-side one. In any case, there are also some client-side solutions.

    Given the possibility, I would recommend the server-side solutions to your problem.

    IFrame element


    The

    Object element


    The element does a similar thing to the