简体   繁体   中英

loading CSS and JS files on specific views in Laravel 5.2

I have CSS and JS files that must only load on certain very specific views in Laravel 5.2.

My boss decided to drop RequireJS which we used to load JS files on our blade templates. Now, we are trying to load dependencies on a native manner.

This is my code:

@extends('layouts.app')
<link href="{{ URL::asset('assets/css/slick.grid.css') }}" rel="stylesheet">
<link href="{{ URL::asset('assets/css/examples.css') }}" rel="stylesheet">
<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
        loadscript('assets/js/jquery.event.drag-2.3.0.js');
        loadscript('assets/js/slick.rowselectionmodel.js');
        loadscript('assets/js/slick.core.js');
        loadscript('assets/js/slick.grid.js');
    });
</script>
@section('page')
//the rest of page

And my "loadscript" function does this:

function loadscript(url, callback)
{
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    head.appendChild(script);
};

This does work, but it feels quite slow, I believe there must be a much better way to have specific css and js file load with laravel on whichever view we want.

It's really important to have the css and js files load only on certain views.

Laravel 5 - Add a stylesheet only if on a certain page/controller (page specific asset)

@extends('layouts.master')

@section('styles')
    <link href="{{asset('assets/css/custom-style.css')}}" />
@stop

If you don't like the @section() idea and just want the dynamic scripts in one place, check out my detailed answer here:

Laravel 5 - Add a stylesheet only if on a certain page/controller (page specific asset)

In summary, using named routes:

<!-- In layout template -->
@if (in_array(Route::currentRouteName(), ['profile', 'register']))
    <script src="example.js"></script>
@endif

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