Import a file containing script and link tags

Asked

Viewed 829 times

0

I am creating a website where on all pages the script and link tags to import the JS and CSS libraries are repeated.

Is there any way for, for example, I create a script.html file (for example) and import this file to all my pages consequently?

Because when adding a new library I need to go page by page and carry out the manual inclusion and thus I would include in only one file and this would go to all others automatically.

I tried by Jquery through the functions load() and html() but I couldn’t, someone has some solution regarding?

Below is an example:

<!-- Última versão CSS do BootsStrap compilada e minificada -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

<!-- Metis Menu -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/metisMenu/2.7.0/metisMenu.min.css" />

<!-- Template SB Admin 2 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/startbootstrap-sb-admin-2/3.3.7+1/css/sb-admin-2.min.css" />

<!-- ícones do Template -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />

<!-- Data Tables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.dataTables.min.css" />
  • You don’t use any technology server-side? This is usually done on the server side.

  • Have you considered the idea of grouping all the scripts in just one file and minify it? There are tools that do this for you and in the end you only need to import one file. The same can be done with CSS.

  • In the case the import, for example, are from several libraries hosted in Cdn, follows below. It’s worth minifying all libraries in one file?

  • Edit the question and add the code directly to it if it is relevant to the problem. Just paste the code into the editor, select it and press the shortcut Ctrl+K to format it properly.

2 answers

1

You may come to use the RequireJS to manage your scripts.

In this case you will only have 3 scripts, one with the RequireJS in itself, one configuration, and the other with the necessary scripts for your page.

Include Requirejs

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.3/require.js"></script>

Setup.:

requirejs.config({
    shim : {
        "bootstrap" : { "deps" :['jquery'] },
        "datatables" : { "deps" :['jquery'] },
        "theme" : { "deps" :['bootstrap','datatables'] }
    },
    paths: {
        "jquery" : "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js",
        "bootstrap" : "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js",
        "datatables" : "https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/jquery.dataTables.js",
        "theme" : "https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.15/js/dataTables.bootstrap.js"   
    }
});

So your page script would be something like this.:

require(['jquery', 'bootstrap', 'datatables', 'theme'], function($){
    $(function(){
        $("#outdoor").carousel();
        $("#tabela").Datatables();
    });
});

0

Like the @jbueno commented, if you use any language on the server side, this treatment will be made much easier on it, be it PHP, Python, C#, Java or any other. Not only easier as recommended. However, if you really want to do something like this on the client side, you can do as described below. I have already said: I do not give any guarantees that it is the best solution, nor if it is recommended to use it in production. It works, but that doesn’t mean it can be used. It’s up to you and your risk.

One way is to manage all files through Javascript. You maintain a list of CSS files and a list of JS files you want to insert on the page, and like Javascript, you scroll through these lists by adding each file, using createElement to set a new element on the page and setting it as the file to be inserted.

Take an example:

// Lista de arquivos CSS a serem carregados na página:
const styles = [
  "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css",
  "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css",
  "https://getbootstrap.com/examples/starter-template/starter-template.css"
];

// Lista de arquivos JS a serem carregados na página:
const scripts = [
  "https://code.jquery.com/jquery-2.2.4.min.js",
  "https://getbootstrap.com/dist/js/bootstrap.min.js"
];

// Objetos de manipulação do DOM:
const head = document.getElementsByTagName('head')[0];
const body = document.getElementsByTagName('body')[0];

// Insere os arquivos CSS na página:
for (let i in styles) {
  let style = document.createElement("link");

  style.rel = 'stylesheet';
  style.type = 'text/css';
  style.href = styles[i];

  head.appendChild(style);
}

// Insere os arquivos JS na página:
for (let i in scripts) {
  let script = document.createElement("script");

  script.src = scripts[i];
  script.type = "text/javascript";

  body.appendChild(script);
}
<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
      <a class="navbar-brand" href="#">Project name</a>
    </div>
    <div id="navbar" class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#about">About</a></li>
        <li><a href="#contact">Contact</a></li>
      </ul>
    </div>
  </div>
</nav>

<div class="container">
  <div class="starter-template">
    <h1>Bootstrap starter template</h1>
    <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
  </div>
</div>

The JS file would be inserted on all pages and, to add a CSS or JS file, simply add it to the list styles or scripts.

It works, but I can’t tell if it is recommended to do something like this in production and what are the weaknesses of the solution.

  • A note, using this technique the scripts and styles are loaded in parallel, so if the bootstrap finishes loading before jQuery, it will raise an exception as it depends on jQuery.

  • Well observed, @Tobiasmesquita.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.