0

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.

1

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.