How to Remove render-blocking JavaScript and StyleSheet in wordpress? - javascript

I'm using wordpress and a theme and made some changes into this theme, when I want to increase page speed Google Page Speed tester says that I need to remove all blocking scripts and styles.
I don't know what is the Render blocking and how to solve this can any one guide me to fix the important issue.
Thanks

I solve Remove render-blocking JavaScript as follows:
<script src="filename.js"></script>
Replace with Following:
<script src="filename.js" defer></script>
<script src="filename.js" async="async"></script>

Lets say for example your <head> section looks like this
<!DOCTYPE html>
<html>
<head>
<title>css - How to Remove render-blocking JavaScript and StyleSheet in wordpress? - Stack Overflow</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="//cdn.sstatic.net/Js/stub.en.js?v=6c41e89d8d17"></script>
</head>
just move the script files to the bottom of the document, or the footer.php file, like so
<!DOCTYPE html>
<html>
<head>
<title>css - How to Remove render-blocking JavaScript and StyleSheet in wordpress? - Stack Overflow</title>
</head>
<body>
<!-- all your other codes here -->
<!-- then your scripts right before the closing body tag -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="//cdn.sstatic.net/Js/stub.en.js?v=6c41e89d8d17"></script>
</body>
</html>
If you move all the scripts out of the head and to right before the </body> closing tag, then that should get rid of that message in google page speed.
Please be aware that it might still give an error/message about CSS stylesheet has render blocking.. well, I would just ignore that , since I want my css to render before the document, so I would not remove that from the <head>.

These solutions are just partial solutions.. methods of inlining, placing scripts at the bottom, using async or defer are not the best solution. If u wanna letting the page load first and then loading the js.
for JS place this code after the </body > tag
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "yourjavascripttoload.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
Src: Patrick Sexton
https://varvy.com/pagespeed/render-blocking.html

Related

How to make an external js file write to the html <script> tags? Via plain JS or jQuery

I'm trying to write a function in an external javascript file linked to the index.html, which when called writes; for example between the <script></script> tags in the index.html file on line 18. Is it possible to do this with plain Javascript or jQuery? If so, how could this be done?
EDIT: I want to only have one script tag in my index.html.
function writeToScriptTags() {
// this function should write alert("Hello") to the <script></script> tags in the index.html file.
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<!-- Dependencies -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" charset="utf-8"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" charset="utf-8"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js" charset="utf-8"></script>
<title>CodeDragon</title>
<link rel="stylesheet" href="/css/master.css">
</head>
<body>
<div id="Dragon"></div>
<input type="text" name="_input" value="" id="_input">
<script src="script.js" charset="utf-8"></script>
<script>
// Javascript file should write alert("Hello") here
</script>
</body>
</html>
If the script tag already exists then you can set it's text/textContent/innerText value to whatever code you want to execute. But the script would need to have been empty beforehand, ie no text not even whitespace, otherwise it would not run.
//use an appropriate css selector to find the correct script
//this just selects the first script it finds
var s = document.querySelector('script');
s.text = 'alert("Here")';
It would probably be better to just create a new script element and add the code to that as then you would not need to worry about wither or not the script tag had already previously been used.
var s = document.createElement('script');
document.head.appendChild(s);
s.text = 'alert("Here")';
And of course if the script is set with a src attribute setting the text of the script will not run any code as it is ignored for externally linked script elements.
You can try this way
Say this is you external.js file
function writeToScriptTags() {
// this function should write alert("Hello") to the <script></script> tags in the index.html file.
}
You can call functions of external.js file between the tags in the index.html file this way.
$.getscript("path/to/jsFile", function() {
writeToScriptTags()
});
Hope you can get an idea.
jQuery solution:
$('script').html('alert(\'Hello\')');
Plain JS solution:
document.querySelector('html').innerHTML = alert('Hello');
Don't add it to the code as a text, beceause it'd be rendered as a plain text and it wouldn't have any functionality.

Can we combine CSS and JS file into one file?

Actually I want to reduce google page speed warning. So I have combine all css external files into one css file and all java script external files into one file java script file. So right now I have two external files(two request), one is css and second one is javascript. Can we combine both file into one file OR two request consider as one request. Is there any produce both file as a one request please let me know.
<link rel="stylesheet" href="../css/eagle/main.min.css" type="text/css">
<script defer src="../js/eagle/init.min.js"></script>
I have seen one link https://www.keycdn.com/support/combine-external-javascript-and-css/, But I am not clear. Any suggestion is very helpfull for me.
You can:
var style = document.createElement('style');
style.innerHTML = cssString;
document.body.appendChild(style);
But I do not think that the two requests is a problem. Funny savings.
You can create one html file(suppose: combined.html) and put all html and css in it using script and style page.
Load combined.html file in your application.
It is depended on which technology you are using to load html into another html. In jQuery below code will help you.
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("combined.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
If you're running serverside, it's doable simply by some sort of includes/partials (e.g. inlcude($file) function in PHP). However, be aware that you're giving up the benefits of caching external files.
Example:
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<?php include("css_js.inc");?>
</head>
<body></body>
</html>
css_js.inc
<style>
*, ::before, ::after {
box-sizing:border-box;
position:relative;
}
</style>
<script>
window.ga = function () {ga.q.push(arguments)};
ga.q = []; ga.l = +new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
No, you can't combine js and css into one file. Maybe this can help to increase the speed of the site.
Where should I put <script> tags in HTML markup?
how to set cache for css/js file

Script tags - not linking (JS platform game)

I'm working through the 'create a platform game' project from Eloquent JavaScript and have an issue with script tags.
In the book we're told to display our level using:
<link rel="stylesheet" href="css/game.css">
<script>
var simpleLevel = new Level(simpleLevelPlan);
var display = new DOMDisplay(document.body, simpleLevel);
</script>
I've tried adding this (together with an additional script tag for my platform.js file) into index.html but the browser is giving nothing back, not sure what I'm doing wrong?
Ensure you are inserting your scripts in the right order:
<!DOCTYPE html>
<html>
<head>
Here you should put your "included" scripts with <script src=...>
</head>
<body>
...
</body>
<script>
Here you should put your first execution, if it needs the html page been completely loaded (as to use document.body).
</script>
</html>
The scripts are being executed as they appear into the page. If you use document, you have to delay the execution until the whole page has been loaded: Either by putting your script at the end of the HTML, either by putting an initialization function within the HEAD, and call it from body onload:
<head>
<script>
function myFunction(){...}
</script>
</head>
<body onload="return myFunction()">
...
</body>
Make sure to include the external JavaScript file you need in a separate <script> tag before your inline script!

Handlebars is not defined

I am new at JS and never tried Handlebars before. I'm trying a very bare-bones example from a tutorial. I have downloaded handlebars-v4.0.5.js from the Handlebars website and included it in my page, as follows, along with a template I precompiled, name-table.js. I'm trying my god damned hardest to complete this tutorial but I can't, because when I run the following code, I get ReferenceError: Handlebars is not defined which I can't for the life of me understand, if the file I downloaded from Handebars' own site is in any way valid.
<html>
<head>
<meta charset='UTF-8'>
<title>Test Page!</title>
<script type='text/javascript'>
function init() {
document.getElementById('button').addEventListener('click', buttonClick, false);
}
function buttonClick() {
var injection = Handlebars.templates['name-table'];
document.getElementById('button').innerHTML = injection;
console.log('hello, world.');
}
window.addEventListener('load', init, false);
</script>
</head>
<body>
<button id='button'>Button</button>
<div id='content'></div>
<script type='text/javascript' rel='js/handlebars-v4.0.5.js'></script>
<script type='text/javascript' rel='js/name-table.js'></script>
</body>
</html>
Edit:
The answer I marked solved the problem. Another error appears in this code, and I want to let anyone reading this know that var injection as defined in this code is a function, not a string as I had thought. This code will work if rel is changed to src as in the answer given, and if we use document.getElementById('button').innerHTML = injection(); (note the parens).
You are not loading in Handlebars (or your name-table script). You currently have the following markup:
<script type='text/javascript' rel='js/handlebars-v4.0.5.js'></script>
<script type='text/javascript' rel='js/name-table.js'></script>
You should be using the src attribute instead of the rel attribute for script tags.
<script type='text/javascript' src='js/handlebars-v4.0.5.js'></script>
<script type='text/javascript' src='js/name-table.js'></script>
The Mozilla documentation does not specify the rel attribute as a valid script tag attribute.
Include this line:
<script src="https://twitter.github.io/typeahead.js/js/handlebars.js"></script>
You are done.
Thanks.

External JavaScript Not Running, does not write to document

I'm trying to use an external JavaScript file in order to write "Hello World" into a HTML page.
However for some reason it does not work, I tried the same function and commands inline and it worked, but not when it's using an external JavaScript file. The part I commented out in the JS file was the previous method I was trying to use. Those lines of could worked when I ran the script from the header, and inline. Thanks
Html file:
<html>
<head>
</head>
<body>
<p id="external">
<script type="text/javascript" src="hello.js">
externalFunction();
</script>
</p>
<script type="txt/javascript" src="hello.js"></script>
</body>
</html>
JavaScript file
function externalFunction()
{
var t2 = document.getElementById("external");
t2.innerHTML = "Hello World!!!"
/*document.getElementById("external").innerHTML =
"Hello World!!!";*/
}
In general, you want to place your JavaScript at the bottom of the page because it will normally reduce the display time of your page. You can find libraries imported in the header sometimes, but either way you need to declare your functions before you use them.
http://www.w3schools.com/js/js_whereto.asp
index.html
<!DOCTYPE html>
<html>
<head>
<!-- You could put this here and it would still work -->
<!-- But it is good practice to put it at the bottom -->
<!--<script src="hello.js"></script>-->
</head>
<body>
<p id="external">Hi</p>
<!-- This first -->
<script src="hello.js"></script>
<!-- Then you can call it -->
<script type="text/javascript">
externalFunction();
</script>
</body>
</html>
hello.js
function externalFunction() {
document.getElementById("external").innerHTML = "Hello World!!!";
}
Plunker here.
Hope this helps.
Script tags with SRC values do not run the contents. Split it to two script tags. One for the include, one for the function call. And make sure the include is before the call.
use onload eventListener to make it simple
<script>
window.onload = function() {
externalFunction();
}
</script>
You're trying to call the function before it has been loaded.
Place the load script above the declaration:
<html>
<head>
<script type="txt/javascript" src="hello.js"></script>
</head>
<body>
<p id="external">
<script type="text/javascript">
externalFunction();
</script>
</p>
</body>
</html>
Also you have a typo:
<script type="txt/javascript" src="hello.js"></script>
Should be:
<script type="text/javascript" src="hello.js"></script>
The script type needs to be "text/javascript" not "txt/javascript".

Categories

Resources