search

Home  >  Q&A  >  body text

javascript - require.js introduces modules and js is loaded on demand

Now there is a need to bring out the resources in the head such as css and js. Now they are introduced using the php template as shown below

html_header.php


index.html


In fact, the resources in PHP are incomplete, and the resources required by each page are also different, and there are some commonalities that need to be extracted.
The current idea is to use require.js to introduce common modules through main.js, and the private modules of each page can be imported now.
I looked at the usage of require online and found it in main.js
require (["jq","react","vue"],function(a,b,c) {some code...})
Introduce the module into the array and pass in the corresponding parameters in the callback to start writing code. But does this mean that all the code is written in main.js?
Now a lot of code is written directly on the page. I just want to introduce modules, such as introducing a JQ and then $(document).ready(function() {})

According to the leader's opinion, it is best to load on demand, such as lifting the header, just like the above php file, writing the common css.js first, and then accepting parameters and passing them to each page. The resources required for parameter customization, please give me some advice. I really don’t know how to do it

某草草某草草2744 days ago962

reply all(2)I'll reply

  • 習慣沉默

    習慣沉默2017-06-12 09:34:34

    Custom developed architecture? This function of PHP loading on demand is implemented in common CMS, such as drupal and joomla. Just add whatever you need to PHP, and then PHP will merge and compress the JS used on the page, so the download capacity will become smaller. For example, drupal7 loads JS through the following code:

    drupal_add_js('misc/collapse.js');

    When using require.js, you really need to write all the JS that needs to be loaded in main.js. If you want to load different JS on each page, then just use PHP to generate the main.js. requireJS is also used on magento2. It has its own mechanism to generate requirejs config, so that each page can be loaded on demand. However, if there are really a lot of JS files, it is better to merge them all and compress them. Otherwise, the loading time may be affected, and a CDN must be used to alleviate it.

    reply
    0
  • 学习ing

    学习ing2017-06-12 09:34:34

    requireJS now supports on-demand loading
    require(["xxxx"], function(xxx){

    var $= require("jquery");
    $(document).ready(function() {})

    })

    reply
    0
  • Cancelreply