Download and run Javascript modules depending on the current page

I have a multi-page website built using Laravel, and now I'm learning how to structure the Javascript interface. Javascript will be for small things, such as showing / hiding components at the click of a button, Ajax calls when submitting a form, adding components to the DOM, resizing / positioning components created in Laravel / Blade.

Pure JS Example:

//navbar.js

export function exec() {
    var hamburger = document.getElementById("hamburger");
    var menu = document.getElementById("menu");

    hamburger.onclick = function() {
        menu.classList.toggle("expanded");
    };
};

// app.js

var navbar = require('./navbar');
/* more imports */

navbar.exec();
/* more executions of modules*/

I split the code into (ES2015) modules , which are then combined using browserify . This means that everything is trying to execute on every page. How should I structure the loading of modules into the main file so that it loads only the necessary modules based on the current page?

React Vue , , , - , , , -.

//progressbar.js
var React = require('react');
var ReactDOM = require('react-dom');

var ProgressBar = React.createClass({
    render: function() {
        return (
            <div className="ProgressBar">
                This is a progress bar.
            </div>
        );
    }
});

module.exports = ProgressBar;

//app.js
import React from 'react';
import { render } from 'react-dom';

var ProgressBar = require('./progressbar');

function renderToElements(toRender, elements) {
  for (var i = 0; i < elements.length; i++) {
    render(toRender, elements[i]);
  }
}

renderToElements(
    <ProgressBar />,
    document.getElementsByClassName('progress-bar')
);

React (, , Vue ) , , Blade , PHP, React, . ? Ajax ?

Laravel + React

//somepage.blade.php
/* other code */
<div class="progress-bar">
    <div class="bar" style="width: {{$product->progress}}%">
        <span>
            <span class="sum">{{$product->progress}}</span>
        </span>
    </div>
</div>
/* other code */

//progressbar.js
var ProgressBar = React.createClass({
    render: function() {
        return (
            <div className="ProgressBar">
                This is a progress bar.
            </div>
        );
    },
    handleResize: function(e) {
        //do something
    }
});

?

+4
1

React router :

<Router>
  <Route name="welcome" />
  <Route name="about" />
  ...
</Router>

, , , , .

0

All Articles