HTML is not reading external Javascript file - javascript

I am trying to write a very simple HTML page that displays a message generated by a JS file. I am somewhat new to HTML / JS and I am certain there is something pretty simple I am missing, but I cannot for the life of me get the page to read the script. When I load the page, it is completely BLANK without any errors in the inspector.
This is the project folder structure:
-Project (folder)
--templates (folder)
----home.html
--src (folder)
----home.js
--styles (folder)
----home.css
Also, I'm pretty sure that my HTML page SEES the script, because when I remove or rename the script, I get an error in the browser's inspector telling me that it cannot find the script. So it SEES the script, it just is not running it for some reason.
Here is the code...
home.html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="../styles/home.css"></link>
<script type="type/javascript" src="../src/home.js"></script>
</head>
<body>
<div id="bodytext"></div>
</body>
</html>
home.js:
(function() {
console.log("I AM READING THE SCRIPT");
document.getElementById('bodytext').innerHTML = "I AM READING THE SCRIPT";
})();
Could some generous soul out there please clue me in to what extremely simple mistake I'm making?
Thank You!

Value for type attribute should be text/javascript as follows:
<script type="text/javascript" src="../src/home.js"></script>

Your script is running before the DOM is completely done loading. If you put your <script> tag right before your closing body tag (</body>), it will run after the DOM is loaded, and you will be able to traverse the DOM like normal.

Value for type attribute should be text/javascript as follows
enter code here
ALong with this you will have to change your java script code as follows, so that script gets executed only when page is completely loaded & document object is availabe.
window.onload = function() {
console.log("I AM READING THE SCRIPT");
document.getElementById('bodytext').innerHTML = "I AM READING THE SCRIPT";
};

What worked for me was adding charset="utf-8" to my css link as well as my javascript script (for me, both did not work). Example:
<link rel="stylesheet" type="text/css" href="css/main.css" charset="utf-8"></link>
<script src="javascript/script.js" charset="utf-8"></script>

Related

JS and CSS not loading in html

I've been following this article (https://dev.to/programliftoff/create-a-basic-webpage-with-css-and-javascript--104i) to get started on building an interactive webpage, but I can't get the JS and CSS to work.
I'm working in Sublime, and I followed this tutorial (https://www.youtube.com/watch?v=oqD5C77Tk3I&feature=youtu.be) to run it through http rather than the file system.
I've double checked the folder paths fifty times (they're just saved on my desktop as 'scripts' and 'styles' in the same folder as my index.html doc), and tried different variations of dots at the start of the paths and slashes both ways, but the JS and CSS just won't load. I've also moved the 'link rel' and 'scripts async src' lines between the head and body tags, but it doesn't seem to make a difference.
My html doc looks like this,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Website</title>
<link rel=“stylesheet” type="text/css" href=“../styles/styles.css” />
<script async src="./scripts/index.js"></script>
</head>
<body>
<h1>Hello, World</h1>
<h4 id=‘date’></h4>
<img src="images/IMG_4945.jpg" alt="My test image">
</html>
My JS doc looks like this,
document.getElementById('date').innerHTML = new Date().toDateString();
My CSS doc looks like this,
body {
text-align: center;
background-color: #ffe6e6;
}
Hard to tell without looking at your file structure, but let's assume you have it like this:
|-Project
|-----css
|---------style.css
|-----js
|---------main.js
|-----index.html
in your index.html you should be calling your css like this:
<link rel="stylesheet" href="/css/style.css" />
in UNIX based OS's (and localhost Windows) / equates to document root. It's best to do this as you're guranteed to always call that file no matter where you copy + paste code to.
Note: In Windows servers / doesn't work - not sure why. Windows just sucks I guess.
Remove the async keyword from your script element. That isn't an asynchronous script and it modifies the DOM before it's ready.
Use jQuery $(document).ready(function() {}); or JS window.onload = function() {}; and remove that async attribute so your script is run in synch with the DOM.
In other words, you cannot edit the document before it has been created. But you are trying to do that with an async and no check for if the document is ready.
../ means parent folder. So:
<link rel="stylesheet" type="text/css" href="styles/styles.css" />
<script src="scripts/index.js"></script>
Double quotation marks in your code are valid? “ -> " Pls check it.

Javascript(Jquery) executes in HTML header but not not when in an external JS file

I know this stuff has been asked before...but I am a bit confused about this still. I have my index.html file and I have a script tag linking to my external JS file. If I only have that script tag the JS does nothing, but if I copy the JS and paste it into it's own script tag in the HTML header it works just fine. There's gotta be something I'm missing with Jquery.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery-3.2.0.js"></script>
<link rel="stylesheet" href="FinalProjectCss.css">
<title>Dustin Naylor - Final Project</title>
<script src="FinalProjectJS.js"></script>
<script>
$(document).ready(function(){
$(".section").click(function(){
if($(this).next().is(":hidden")) {
$(this).next().slideDown("fast");
} else{
$(this).next().hide();
}
});
});
</script>
</head>
<body>
<span class="section">Click Me</span>
<div class = "hiddenDiv">
Oh hey there.
</div>
</body>
</html>
So the code in the last script tag that is Jquery stuff is exactly copied into a separate JS file named FinalProjectJS.js. In the current state this code is in it works as desired, but when I remove that chunk of code from the html file it doesn't work....Sorry for my nubishness, I'm rather new and any help would be great! thanks!
Can you write the contents of your jquery file: FinalProjectJS.js? The syntax for calling the external file seems to be correct. So I'm thinking it might be something about the path or the jquery external file contents itself. Make sure you don't include <script> tags on that file. Here's a sample.
Another thing, last time I've worked with jquery, I can't directly see it take effect when both my files are stored locally. It had to be stored in a server first, then accessed by my PC. Only then did my jquery took effect. A dev I worked with added some text to my Google Chrome's properties (target) so that even if my file is not stored in a server, I can see jquery take effect even if both my HTML and jquery files are stored locally.
...sorry, I'm not allowed to comment yet to clarify your post.
You must add the jQuery script tag before FinalProjectJS.js for the jQuery snippet to work.
<script src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous">

Avoid Render Blocking by plugins which have both css and js dependencies

I am using a jQuery plugin it has plugin.css and plugin.js as dependencies and code is in script.js. I cant have plugin.js and script.js merged because i am using plugin only on one webpage of my website.
In order to make sure plugin.css is loaded before execution of plugin.js and script.js, normally I have no option but to have plugin.css in <head> which causes render blocking(until all resources in head are loaded,
browser doesnt render html).
Normal Way: Having CSS in <head> and JS before </body>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/css/plugin.css">
</head>
<body>
// content goes here
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script src="/js/plugin.js"></script>
<script src="/js/script.js"></script>
</body>
</html>
Proposed Way: Load CSS and JS via ajax calls and inject them when all of them are loaded, using jQuery $.when promise
<!DOCTYPE html>
<html>
<head>
</head>
<body>
// content goes here
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script class="load-plugin">
$(document).ready(function(){
var loadPlugin = {
css : $.ajax({ url: $(".jquery-plugin-css").data("src") }),
js : $.ajax({ url: $(".jquery-plugin-js").data("src")}),
};
var scriptJs = $.ajax({ url: $(".script-js").data("src") });
$.when(loadPlugin.css, loadPlugin.js, scriptJs).then(function(){
loadPlugin.css.done(function(data){
$(".jquery-plugin-css").html(data);
});
loadPlugin.js.done(function(data){
$(".jquery-plugin-js").html(data);
});
scriptJs.done(function(data){
$(".script-js").html(data);
});
});
});
</script>
<style class="jquery-plugin-css" data-src="/css/plugin.css"></style>
<script class="jquery-plugin-js" data-src="/js/plugin.js"></script>
<script class="script-js" data-src="/js/script.js"></script>
</body>
</html>
This improved my first render time from 3.4 secs to 2.4 secs and total page load time from 8.5secs to 8secs.
But this has some limitations:
Publicly hosted urls cant be used because the urls inside the plugin files like background-images inside css files if mentioned relative to their directory then the path changes after code is pasted into html.
As the injected code is not part of the source files or external scripts they cant be debugged in developer tools.
This way of lazyloading plugins has pros and equal amount of cons. Can anyone suggest is it worth it to do it this way or any better way to do things.
What I would try is:
Combine the JS files so that the dependent code is after plugin.js
Insert a script at the bottom of the page to dynamically load the CSS first and the combined JS second. If you need example code, you might look at https://github.com/filamentgroup/loadJS/ and https://github.com/filamentgroup/loadCSS/.
Using this approach, neither the CSS nor the JS blocks rendering. The CSS is appended to the DOM, so there should be no problems with relative URLs.

How to specify, different JS file for different view page in play framework?

How do we define different javascript files for different view pages in play framework??
One way is to=>
#main(title, """
#*JS CODE*#
"""{
//Template Codes
}
And in main template, use it like=>
#(title,stringJS){
<script>
#Html(stringJS)
</script>
}
But what if the JS code is to be used in not all pages but selected few, the dev can't copy the JS code in every relative view page.In my case all the javascripts are loaded on the footer, which is a seperate template.
How do we solve this problem??
Any help is appreciated, thank you!
It's described in the Common templates use cases doc , section : 'moreScripts and moreStyles equivalents'
In very short it works like this (view)
#moreScripts = {
<script type="text/javascript">alert("hello !");</script>
}
#moreStyles = {
<style>background: pink;</style>
}
#main("Title", moreScripts, moreStyles){
Html content here ...
}
and in main.scala.html start with:
#(title: String, moreScripts: Html = Html(""), moreStyles: Html = Html(""))(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
#moreStyles
<script src="#routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
#moreScripts
</head>
<body>
#content
</body>
</html>
I came up with my solution,thanks to this Helpful SO post, what I did was:
#main(title, """
#*NO JS CODE, but declaration itself*#
<script src="/assets/javascripts/libs/main.js" type="text/javascript"></script>
<script src="#routes.Assets.at("javascripts/libs/main.js")" type="text/javascript"></script>//Doing this gives out errors, so I had to hardcode the "src" location
"""{
//Template Codes
}
If there is more efficient way to solve this issue, ideas are welcome, because hard-coding src isn't an efficient way of dealing with this issue, imo.

Meteor.js: <script> tag doesn't work inside <body>

A simple script tag inside the body tag doesn't seem to work. The alert doesn't get triggered in the code below:
<body>
<script type="text/javascript">
alert('Hello');
</script>
{{>main}}
</body>
Any idea why?
Edit:
Just tried it with a fresh meteor app, no alert tag still:
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript">
alert('Hello');
</script>
{{> hello}}
</body>
<template name="hello">
<h1>Hello World!</h1>
{{greeting}}
<input type="button" value="Click" />
</template>
Weird thing is when I copy paste the source of the html, made a new html page, and the alert will work.
Edit3: I deployed this app here: http://alert-in-body-test.meteor.com/
Do you get an alert box?
This question is still relevant in the current version of Meteor (version 0.5.4) so I wanted to describe how to include script at the end of the body.
To execute javascript at the end of the body, register a Handlebars helper and put the relevant code there, like this:
In client.html:
<body>
{{renderPage}}
{{afterBody}}
</body>
...
In client.js:
if (typeof Handlebars !== 'undefined') {
Handlebars.registerHelper('afterBody', function(name, options) {
$('body').append('AFTER BODY');
});
}
(For a great description of why this is required, see Rahul's answer to a similar question here: https://stackoverflow.com/a/14002991/219238 )
Its working for me
in onrender call this jquery
$.getScript('yours url')
It should work.
I have just pasted this inside one of my projects and it worked.
Your {{>main}} is strange for me tough. Also make sure that <body> is inside <html> tag.
Meteor is constructing the entire DOM from Javascript by rendering your page as a template -- the 'source' for your page as seen by the browser is basically:
<script type="text/javascript" src="/5a8a37bef5095c69bcd3844caf3532e1ba6d49bf.js"></script>
I can't find a definitive page stating that embedding a script tag in a template like this won't cause it to be executed, but it definitely feels against the spirit of what the framework is trying to achieve.
If the point is to achieve a clean separation of your markup and logic then why put it in the template. A better solution would be to use the meteor.startup call
Instead of looking the rendered html at developer tools, try looking the real downloaded html.
You will find a (probably) empty tag, with tons of script tags inside the .
In other words, the body of your meteor application is not the body of the final html, it's just your main template.
Instead, this ton on scripts shipped by Meteor, will load your templates.
So, your code will not run, cause it's been placed there. It's like when you manipulate DOM (with jQuery, for exemple), placing a script tag in DOM, after it's loaded. This script tag will not run.

Categories

Resources