I can't link javascript files as commonjs modules - javascript

I have:
test.json - contains the content to be uploaded into the HTML page
test.js - contains the function that sends an Ajax request to the JSON file, parses, compiles with Handelbars Temlate and puts the content into the HTML page (using innerHTTML).
addcontent.js - javascript file which calls the function from the test.js file
index.html - contains the Handlebars Template, Div
where the content will be placed after processing, and a link to the
addcontent.js.
Everything works, if inside index.html there is a link directly to test.js.
Everything works if I wrap the code inside test.js in a function with variables and call this function in the same file.
But if I call this function from addcontent.js and connecting addcontent.js and test.js using commonJS module approach, it does not work.
Probably I made a syntax mistake somewhere, but I don't see it.
P.S. I use NodeJS, NPM, HTTP-server and I'm going to merge all javascript files using browserify after all
//test.js
module.exports = function addContent (jsonDir, templId, finId){
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', jsonDir);
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById(templId).innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById(finId).innerHTML += template(response);
})
}
/* test.json */
{
"time": "03:47:36 PM",
"milliseconds_since_epoch": 1471794456318,
"date": "08-21-2016-123",
"test": "lalala 123"
}
/* addcontent.js */
var addContent = require('./test');
addContent("json/test.json", "date-template", 'testData');
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="handlebars-v4.0.5(2).js"></script>
</head>
<body>
<!-- template-1 -->
<div id="testData"></div>
<script id="date-template" type="text/x-handlebars-template">
Date:<span> <b>{{date}}</b> </span> <br/> Time: <span><b>{{time}}</b>
</span>
</script>
<script type="text/javascript" src="addcontext.js"></script>
</body>
</html>

Related

add script dynamically to DOM before other scripts are executed

I do a simple check if js file exists. If not, I try to load it dynamically before other scripts from bottom of a page are loaded. Is it possible to do? Here is fiddle where bottom script is executed before thus giving errors.
https://jsfiddle.net/vnfxus56/1/
thank you.
<div id="top">top</div>
<script>
doesFileExist('https://ajax.googleapis.com/ajax/libs/nonexistingfile.js');
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
if (xhr.status == "404") {
console.log("File doesn't exist");
var script = document.createElement('script')
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js'
document.head.append(script)
return false;
} else {
console.log("File exists");
return true;
}
}
</script>
<script>
//this is printed out of a variable as a bunch of inline jquery code
$("#top").fadeOut();
</script>
below I posted the code that could await until the "xhr" request is finished. I used the "async functions" concept in javascript that you can read more about it here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
function afterLoad() {
console.log('DOM fully loaded and parsed');
$("#top").fadeOut();
}
#top {
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>xhr</title>
<link rel="stylesheet" href="style.css">
</head>
<body onload="afterLoad()">
<!-- using "onload" method is necessary to run the script after finishing "xhr" -->
<div id="top">top</div>
<script>
let urlToFile = 'https://ajax.googleapis.com/ajax/libs/nonexistingfile.js';
function doesFileExist(urlToFile) {
return new Promise(resolve => {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
if (xhr.status == "404") {
console.log("File doesn't exist");
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js';
script.setAttribute("async", "");
console.log(script);
document.body.append(script);
// your custom script file
var script2 = document.createElement('script');
script2.src = 'myscript.js'; // define the address of your javascript file.
script2.setAttribute("async", "");
document.body.append(script2);
resolve(false);
} else {
console.log("File exists");
resolve(true);
}
});
}
async function asyncCall(urlToFile) {
console.log('starting');
const result = await doesFileExist(urlToFile);
console.log(result);
console.log("finished");
}
asyncCall(urlToFile);
</script>
</body>
</html>
I think it is useful to mention that I changed your code from two "script" tags to only "one" and used "two" functions in it. one of them works on "xhr" request and adding script tags, and the other forces the code to wait until the xhr request is finished. I added "$("#top").fadeOut();" part of your code to a separate script code that is in the same directory and appended the script tag in first function.

Importing header file in html file is not working properly

I have a header.html and header.js files because I want to use the same header through my webpages.
In header.js file, on window load I want it to console.log("header file loaded").
I also have index.html and index.js file for my homepage. In index.js, on window load I want it to console.log("index file loaded")
I called header.html in index.html file, in order to import the header for the homepage. This works fine.
based on js files the console output should
header file loaded
index file loaded
The problem I am having is that
it seems like header.js and index.js cannot work simultaneously
only the last referenced file gets outputed in the console
for example this format
<script src="js/header.js"></script>
<script src="js/index.js"></script>
will output
index file loaded
and this
<script src="js/index.js"></script>
<script src="js/header.js"></script>
will output
header file loaded
I use the code to import header.html in index.html
<head>
<div data-include="header"></div>
</head>
<body>
<script>
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var file = $(this).data('include') + '.html';
$(this).load(file);
});
});
</script>
</body>
this is the content of both js file
function retrieveInfo(data) {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/Sellers/' + userId).once('value').then(function(snapshot) {
console.log(userId)
console.log("index file loaded")
});
}
})
}
what am I doing wrong and how can I fix it to have both js file called?
You are doing it in a wrong way, .load() is used for loading HTML contents. You should be using .getScript(), to load the js and execute it.
According to docs:
.load()
Load data from the server and place the returned HTML into the matched element.
.getScript()
Load a JavaScript file from the server using a GET HTTP request, then execute it.
Here is an example for using getScript:
$.ajax({
url: url,
dataType: "script",
success: function() {
alert("script loaded");
}
});
In your case it would be:
$(function(){
var includes = $('[data-include]');
jQuery.each(includes, function(){
var JS = $(this).data('include') + '.js';
var file = $(this).data('include') + '.html';
$(this).load(file);
$.ajax({
url: JS,
dataType: "script",
success: function() {
alert(file + " loaded");
}
});
});
});

Function was not defined in javascript?

I have two script files - one is perl-cgi and the other is javascript. Inside the cgi script I have written the Javascript function for retrieving data from a text file (using ajax). I then pass the contents of the data into another function called main_function(). This writes into the javascript file (seq_new.js). When I load the page, the console.log reports main_function was not defined. Then I refresh the page and the result displays. I don't know why it behaves this way.
The Perl script as follows:
#!/usr/bin/perl
print "Content-type:text/html\n\n";
use CGI;
my $a= new CGI;
my $processId = $a->param("processId");
.
.
my $file_path = "/$processId/$file_name[1]";
print <<HTML;
<!DOCTYPE html>
<html>
<head>
<title>RepEx - Result</title>
<script type="text/javascript" src="/min.js"></script>
</head>
<body>
<script>
file_load("$file_path","$filename");
function file_load(f1,f2)
{
var fileNm = f2;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
var pt = xhttp.responseText;
main_function(pt,fileNm,"$file_path",$file_cnt,"$head_st");
}
};
xhttp.open("GET", f1, true);
xhttp.send();
}
</script>
<script type="text/javascript" charset="utf-8" src='/seq_new.js'> </script>
</body>
</html>
My javascript file contains this:
function main_function (a,file_seq,main_file,fle_cnt,header_set)
{
.
..
}
The problem I am encountering
Loading the page for the first time, the console.log reports that the main_function was not defined and no results are displayed. After refreshing the page (by pressing F5 or clicking the reload button), the result is displayed.

Can't call external javascript function from JQuery

I have a script file called trim.js. I'm trying to call a function prepareURL() from this file in my index.html file. However I'm getting the following error:
ReferenceError: Can't find variable: prepareURL
I make sure to import my script doing the following:
<script type="text/javascript" src="./js/trim.js">
</script>
<script type="text/javascript">
$(function() {
$('#simple_sketch').sketch();
$('#simple_sketch').sketch('color','#fff');
$('#simple_sketch').sketch('size','6');
});
function predict() {
//Create Image URL
var imageURL = prepareURL('#simple_sketch')
}
The function in my trim.js file looks like this:
function prepareURL(c) {
//My code
}
How can I call prepareURL from my index.html file?

Phonegap - How to call one javascript function in another file from index page?

I am an iOS and PhoneGap newbie. I have the index.html file and a javascript file called MyClass.js.
In my MyClass.js, I have a function -
var MyClass = {
testfunc: function() {
navigator.notification.alert("Success : \r\n");
}
}
I am trying to call it from the index.html function like -
MyClass.testfunc();
In my Phonegap.plist file I have an entry MyClass-Myclass as a key-value pair with the type String. However I don't get the alert. What am I doing wrong?
Have you included the following in your index.html:
<script src="MyClass.js"></script>
This will allow you to use the MyClass.js functions in your index.html file
Your markup for your alert is wrong...
navigator.notification.alert(
'Some Alert Text here', // alert message
successCallback, // callback function
'Alert Title, // alert title
'OK' // button text
);
Hi can you try following code:
// MyClass.js
var MyClass = {
testFunction: function() {
alert("hi there");
}
};
// index.html
<html>
<head>
</head>
<body>
<script src="MyClass.js"></script>
<script src="phonegap-1.3.0.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", function() {
navigator.notification.alert("hi there \r\n");
//alert("hi there \r\n");
});
</script>
</body>
</html>

Categories