简体   繁体   中英

What's the best (fast) way to load javascript in different pages?

What's the best way to load fast javascript in different pages ? Should my custom javascripts go separate for each page or all custom javascripts should be present only in 1 common custom.js file and include this file in footer ?

require_once($header);
include_once($page2.php);
require_once($footer); 
<script src="js/custom-page2.js"></script>//separate for each page

require_once($header);
include_once($page1.php);
require_once($footer); 
<script src="js/custom-page1.js"></script>//separate for each page

OR

//in footer.php include all js in 1 file
<script src="js/all-custom.js"></script>

If all pages share the same scripts using one script will be better.

If they use different scripts you can cut out what each page DOESN'T need and save on HTTP requests.

Or a mixture of the two.

So...it depends?

Basic rule: If you don't need it, don't load it.

I advise you to create your html page by including in this order :

  • HTML wrap all
  • Head (with style in one page for example)
  • Body with:
    • Javascript modules
    • Main HTML DOM
    • Javascript DOM modifiers and launchers

Same like this :

<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <script type="text/javascript" src="modules.js"></script>
    <div class="body"></div>
    <script type="text/javascript" src="functions.js"></script>
</body>
</html>
  1. it's good idea to put all js in header (browser will not render page until all header files are loaded, at least in theory).

  2. browser (proxy etc) will cache your js, so it's not going to be fetched from your site on every request. browser will only check if file has changed.

  3. in most cases browser will keep single connection for all requests, however it still has to ask for every single js file if it hasn't changed. i keep js logic in small seperate files during development, but then i merge them for production.

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