javascript error - Scripts are not found - javascript

Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var path = '/Scripts/';
document.write('<base href="' + path + '"/>');
</script>
</head>
<body>
<h1>WELCOME</h1>
<script src="test.js"></script>
</body>
</html>
test.js
console.log("Message from external script");
output
error.png
Here you can see, first it try to load the script from body tag before it get the actual base href path from script section.
Is there any way to get come out from this error? I mean not to load body script until base href set.
Once the base href set, it executed successfully.
Thanks.

The behavior you're seeing is (somewhat) browser-specific, and is related to your use of document.write to set the base href dynamically.
Chrome and Firefox try to load the page resources before applying the document.write, then updates those urls and tries again after you set the page <base>. Safari appears to not do this; it uses the inserted base href immediately. I have not tested other browsers.
(In all browsers the <base> tag, whether static or dynamic, needs to appear in the document before any links that depend on it.)
Other than the extra network request this seems to be harmless (see below), but you could avoid it by using a static <base> tag instead of dynamically writing one in, or by setting the full path on the <script> tag instead of depending on the <base>.
(re "harmless": I checked the case where a test.js exists both at the root level and inside the "/Scripts" directory. Dynamically inserting the "/Scripts/" base href did not cause both scripts to execute in Chrome: successful network requests for both test.js files were made, but only the code in "/Scripts/" was executed. So the browser makers have handled that edge case already. Good job, browser makers!)

You Can use this code
<script src="./scripts/test.js" type="text/javascript"></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">

HTML is not reading external Javascript file

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>

Does angularjs gets loaded on fallback of jQuery?

In the below code,
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Falback procedure</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script type="text/javascript">
if(typeof jQuery === 'undefined')
document.write('<script type="text/javascript" src="../localfolder/jquery.js"></script>');
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.js">
</script>
</head>
<body>
<p>Hello</p>
</body>
</html>
considering a scenario, where google CDN has reach-ability issues that triggers fallback mechanism of loading local jQuery library(sitting in webserver).
In such scenario, Does angularjs library get loaded? after executing document.write
You have two problems with that code that are likely to be making it not behave as you expect:
You have a literal </script> inside a script block. It doesn't matter that it's inside a string, it terminates the block it's in. You have to break it up so the browser doesn't see it as the end of the block:
<script type="text/javascript">
if(typeof jQuery === 'undefined')
document.write('<script type="text/javascript" src="../localfolder/jquery.js"><\/script>');
// Note the \------------------------------------------------------------------^
</script>
The \ there is meaningless in JavaScript, but prevents the browser from seeing </script> and thus from ending the script block prematurely. Other ways you see it done are '....<' + '/script>' or '...</scr' + 'ipt>', etc.
Your src on the Angular script is incorrect, so it won't work whether jQuery loads or not (or from where). You've made the URL relative to the path of the page, but you need to make it at least protocol-relative by adding //:
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.0/angular2.js">
</script>
<!-- here --------------------------^ -->
In a comment, you asked
I was wondering, whether document.write was an asynchronous execution
No, it happens immediately when the function is run. In your case, since the function is at the top level of a script tag with no special attributes, the HTML parser has to screech to a halt and run that JavaScript code, processing any tokens the JavaScript code outputs via document.write, and waiting until the JavaScript code finishes before moving on to the Angular part.
The browser may well be able to scan ahead to preload the angular.js file, but it won't execute the contents of that file until the parser has reached that file's script tag, because the order in which scripts execute is well-defined (e.g., in document order) unless you use the async or defer attributes.

letter in quotes appearing just after body tag

We've just launched our new Magento site and the letter 'c' is appearing in quotes immediately after the tag. It's not showing up before on my local machine or on our QA site, I've checked the template files and it is not there either. I'm almost certain it can not be a code issue as we have the same code running locally and on our QA site under version control with GIT.
We've cleared the cache and I've tried checking to see if JavaScript was inserting it with the chrome dev tools but could find nothing.
Strangely, the 'c' is not in the view source document but I can see it with the chrome inspector.
I also don't think it can be coming from Magento CMS Pages/Blocks as it loading immediately after the tag.
thanks for the link. after reviewing the page source, you have an extra c character in the header area:
<!-- END GOOGLE ANALYTICS CODE -->
c<script type="text/javascript">//<![CDATA[
var Translator = new Translate([]);
//]]></script>
Notice that c before the script tag?
Just in support to Benny Lin's very helpful answer.
What was happening was we had our Google Analytics code loading from a template file which contained the stray letter 'c'. We could see this on our local machines as this templates was disabled in the Magento admin settings, but not on production.
This issue seems to demonstrate that when a stray letter appears within the <body> tags on your dev tools inspector and not the view source page it may be because it is in the <head> section. The browser seems to push all poorly formatted html from the <head> section into the <body> section when rendering.
For example if you open the below html in the chrome browser you will see what I mean:
<!DOCTYPE html>
<html>
<head>
c<title>Title of the document in head</title>
<script type="text/javascript">
var test = "test";
</script>
</head>
<body>
The body of the document......
</body>
</html>
Also while we were searching for the stray letter, we were ably to remove it with the below JavaScript that targets the offending XML node in the DOM with an XPath expression and removes that node only.
<script type="text/javascript">
function _x(STR_XPATH) {
var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
var xnodes = [];
var xres;
while (xres = xresult.iterateNext()) {
xnodes.push(xres);
}
return xnodes;
}
jQuery(_x('//html/body/text()[contains(.,"c")]')).remove();
</script>

Categories

Resources