loading CSS and JS files on specific views in Laravel 5.2 - javascript

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

Related

Calling a JS function from a second file using ASP.NET

I have an ASP.NET web application that makes use of a large Javascript file to enable front-end functionality. The issue is that since this web application is growing in size the Javascript file is growing in size along with it.
I want to remove some of my larger functions out of my main javascript file site.js and instead contain them inside a second file. My aim is to declutter the main JS file and increase readability etc.
If this were a normal web application I'm sure I'd be able to use JQuery to achieve this through use of the .getScript() however I've tried using this function to pull in a separate script with a simple alert function and I get a reference error saying that my alert function is undefined. I have included both scripts within my ASP.NET _Layout view, but still it doesn't work.
Below is what I am doing currently, what do I need to do to be able to call a JS function held inside another file from site.js?
site.js
$(function() {
$(document).ready(function() {
$.getScript("../site2.js");
sendAlert();
});
//... other js
});
site2.js
$(function() {
function sendAlert() {
alert("site2 file");
}
});
_Layout
<!DOCTYPE html>
<html>
<head>
<script src="~/js/site2.js"></script>
<script src="~/js/site.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css" integrity="sha384-88btmYK8qOHy4Z2XuhkWZjUOHICKYe1eSDMwaDGOAy802OCu6PD6mwqY5OwnfGwp" crossorigin="anonymous">
<script defer src="https://use.fontawesome.com/releases/v5.1.0/js/all.js" integrity="sha384-3LK/3kTpDE/Pkp8gTNp2gR/2gOiwQ6QaO7Td0zV76UFJVhqLl4Vl3KL1We6q6wR9" crossorigin="anonymous"></script>
</head>
<body>
#RenderBody()
#RenderSection("Scripts", required: false)
</body>
</html>
I think that you can do this:
$(function() {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "../site2.js");
document.getElementsByTagName("head")[0].appendChild(script);
});
Cheers - Vinh

SEO impact of CSS Stylesheet dynamic loading with JavaScript

Because my webpages are a bit heavy, I decided to use a preloader. The purpose of a preloader is to show some content before the main content loads, engaging the user from the start. Therefore it is very important to show preloader ASAP.
There is a slight problem though. Browser will typically wait for all CSS to be loaded before attempting to display and render HTML. This can be problematic if the document contains several biggish stylesheets.
So, my solution was thus:
<!-- In the head: -->
<noscript>
<link rel="stylesheet" href="/big-css1.css">
<link rel="stylesheet" href="/big-css2.css">
<link rel="stylesheet" href="/big-css3.css">
</noscript>
<script>
function LoadCSS(path) {
var head = document.getElementsByTagName('head')[0],
link = document.createElement('link');
link.setAttribute('href', path);
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
head.appendChild(link);
}
</script>
<style>
/*preloader CSS is here*/
</style>
...
</head>
<body>
<div id="preloader">
Some nice content here
</div>
<!-- Main content starts below: -->
<div id="wrapper">
<script>
//hide main content until its loaded
//use JS and not CSS to support those with JS disabled
var el_preloader = document.getElementById("preloader");
var el_wrapper = document.getElementById("wrapper");
el_preloader.style.display = "block";
el_wrapper.style.display = "none";
LoadCSS('/big-css1.css');
LoadCSS('/big-css2.css');
LoadCSS('/big-css3.css');
</script>
...
<!-- After jQuery has been loaded -->
<script>
jQuery(window).load(function() {
document.getElementById("wrapper").style.display = "block";
jQuery('#preloader').fadeOut(1000, function () {
jQuery('#preloader').remove();
});
});
</script>
So, basically, if the use supports JavaScript, then JavaScript handles loading of stylesheets, and if JS is turned off, then the stuff inside the <noscript> tag is parsed and thus stylesheets are loaded normally.
This setup works fine in modern browsers, however I am not sure what impact it will have on SEO, considering Google and others are now evaluating user experience on the websites, and for that they need to parse CSS. Are they smart enough to render the website correctly with this solution? ARe there any adverse impacts on SEO with preloaders in general?
Thanks.

Optimizing CSS/JS imports for Static website using common a JS document

Coming from a server side programming background, this might be a noob question.
Currently I have css laid out like below and also JS in a similar fashion.
<link type ="text/css" href="css/bootstrap.min.css" rel="stylesheet">
<link type="text/css" href="css/custom.css" rel="stylesheet">
<link type="text/css" href="css/template.css" rel="stylesheet">
But I have around some 40-50 html pages remaining to be coded and dropped in and all pages share the same CSS/JS more or less.So, how do I avoid this boilerplate typing.Can I just do like below
var navBar = ['<div class="hi-icon-wrap hi-icon-effect-9 hi-icon-effect-9a" text-align="">',
'<a class="hi-icon hi-icon-fa-home" style="text-decoration:none!important" href="index" title="Blah"></a>Home',
'<a class="hi-icon hi-icon-fa-wrench" style="text-decoration:none!important" href="tools" title="Blah"></a>Tools',
'<a class="hi-icon hi-icon-fa-folder-o" style="text-decoration:none!important"href="blog" title="Blah"></a>Blog',
'<a class="hi-icon hi-icon-fa-user" style="text-decoration:none!important" href="about" title="Blah"></a>About Me',
'</div>'].join('\n')
I mean using the same logic to print out <script> and <link> tags?If so, does it have any disadvantages or is there a better way to do it.
Since you are using Jekyll, you should just use the Includes feature built in.
All you do is have a _includes folder in the root folder of your project, and add a js-css.html file in there with all your <script> and <link> tags to reference the JS and CSS files.
Then in your template, you would just have:
{% include js-css.html %}
in your <head> tag everywhere.

How to implement a CDN failsafe for css files?

For javascripts hosted on CDN, I can always add some scripts below it to check if it is loaded successfully:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
if (!window.jQuery) {
var script = document.createElement('script');
script.src = "/js/jquery.min.js";
document.body.appendChild(script);
}
</script>
I also used some hosted css files, like bootstrap. How can I reiliably check if it is loaded on the web page, and provide a fail-safe if isn't?
-----EDIT--------
And, by the way, should I use:
document.body.appendChild(script);
or:
document.write("<scr"+"ipt>"...);
Which one guarantees execution order in all browsers?
you could use onload and onerror events...
<link rel="stylesheet" type="text/css" href="cdnurl/styles.css"
onload="alert('loaded')" onerror="javascript:loadCSSBackup()" />
javascript:
function loadCSSBackup(){
var css = document.createElement("link")
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", 'backup/styles.css');
document.getElementsByTagName("head")[0].appendChild(css);
}
regarding 2nd question, you should avoid using document.write. Appending to body or head as in the code above should be fine.

HTML5 Boilerplate and cirical rendering path / deffering scripts and styles

I used to build my websites based on the HTML5 Boilerplate: styles and modenizr in the head, jQuery (google CDN or hosted file) and scripts before the closing body tag. Something like that:
<!DOCTYPE html>
<!-- modernizr conditional comments here -->
<html class="no-js">
<head>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Now I want to remove all render-blocking below-the-fold css and js as suggested by Googles PageSpeed Insight.
How do I defer the css and js files including the jQuery library loaded from google?
What should I do about modernizr?
To remove this particular warning you need to do the following:
defer the load of all external CSS until after page onload
defer the load of all external JS until after page onload
In practice that means you need to do the following:
split your CSS into that required to avoid the "flash of unstyled content" (FOUC) and the rest
split your javascript likewise
inline the CSS and JS that is required
defer the load of the other CSS and JS until after page onload.
Using build tools is the only sane way of doing this. You can do it with various Grunt tools, or with the ant-based H5BP Build Script.
The basic method of deferring loads is as follows:
(function () {
// Load jQuery after page onload
function loadJS() {
var url = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
var n = document.createElement("script");
n.src = url;
n.onload = loadJS1;
document.body.appendChild(n);
}
// Load some JS after jquery has been loaded.
function loadJS1() {
var url = "js/main.js";
var n = document.createElement("script");
n.src = url;
// Continue chaining loads if needed.
//n.onload = loadJS2;
document.body.appendChild(n);
}
// Check for browser support of event handling capability
if (window.addEventListener) {
window.addEventListener("load", loadJS, false);
} else if (window.attachEvent) {
window.attachEvent("onload", loadJS);
} else {
window.onload = loadJS;
}
})();

Categories

Resources