Load external file then run function from file - javascript

I'm trying to load another JS file from JS (because the url can change depending on what the user selected and load both would cause conflict issues) and then right after loading the file run a function from the file. I need to run a function and I can't just run code because the function requires client inputs. How can I do this?
In this example, I haven't included the dynamic URL part because that works. Also, no 2 attempts were tried at once. I tested them all separately. None of them worked. This is what I've tried:
var url="file.js", script = document.createElement('script');
script.setAttribute('src',url);
script.setAttribute('id','option');
document.head.appendChild(script);
// code attempt 1 at loading the function:
fileInit(param1);
// code attempt 2:
document.getElementById("option").onload = fileInit(param1);
// code attempt 3:
script = document.getElementById("option");
script.onload = script.onreadystatechange = fileInit(param1);
// code attempt 4:
document.getElementById("option").addEventListener("load", fileInit(param1));
I just want to load the file is JS (so I can have a dynamic url) and then when the file is loaded run the init function defined in the file. I also don't want to use jQuery. I want the code to be vanilla JS. I know you can use jQuery.getScript().

In both files you should have this statement exports.__esModule = true; and in the export file you do this for each thing you want to export exports.thingToExport = thingToExport; then you import like so:
var file = require("path/to/file");
file.thingToExport;
Edit: This question explains what you do in typescript to get this node code.This also works in modern browsers import functions from another js file and is probably a duplicated.

Related

My JavaScript code won't run after jquery ajax call

jQuery code in a script1.js file
$(document).ready(()=>{
$.ajax({
method:"GET",
url:"someurl",
success :
(data,status,xhr)=>{
//Create some html buttons after I get the data
//I want to append the js file here(the JavaScript file adds some event functions to the newly created buttons.I know i can add the event listeners to the button directly here but for some reason I prefer to have the code in a separate js file)
//This does not work
$('head'). append('<script src="script_here"></script>')
}
})
})
JavaScript code in a script2.js file
document.addEventListener('DOMContentLoaded',ready)
function ready (){
document.querySelector('button').addEventListener('click',()=>{
//Do some other stuff
})
}
I have tried appending the script2.js file through the jQuery but its not working.
I do not want to have everything in one file for easy debugging, and I need to have both vanilla js and jQuery in my project.
If you just want to load an external js file after the ajax call. Then I will show you using in Pure JS. As I have encountered similar issue, so it might help you.
(data,status,xhr)=>{
const fileref = document.createElement('script');
fileref.setAttribute('type', 'text/javascript');
fileref.setAttribute('src',
'https://speechanywhere.nuancehdp.com/3.0/scripts/Nuance.SpeechAnywhere.js?_r=' +
(Math.random() * Math.pow(10, 18)).toString(32)); // the math random will help from cache errors each time you load
document.getElementsByTagName('head')[0].appendChild(fileref);
}
Import and use external JS Library

How do I add a personal script to an existing node.js library?

I have a local copy of the hls.js library and I need to include a personal script with custom functions in it.
How do I go about adding a new script to the library and how do I use the function written in the new script?
Let's say that I want to add a script called hello.js that contains a function that logs "Hello World".
When I call that function in my main.js I need it to execute.
Any ideas on how to do this?
Currently, I'm getting an error that the function is not defined.
I placed the hello.js script in the src folder of the library but this (as expected) doesn't seem to work.
It should be possible to add functions to the exported hls.js object.
Your custom-script.js:
var hls = require('hls.js')
hls.customFunc1 = function () {
}
hls.customFunc2 = function () {
}
on main.js:
require('custom-script')
// your code follows
Any other code would be able to use the custom functions by just require'ing hls.js.

Getting Javascript files using Rawgit

I'm trying to include a JS file in my website via Ajax by getting it from one of my GitHub repositories, using Rawgit. For some reason, it doesn't work when I use the development or production URLs, but when I use the raw version of my files directly from Github, the problem stops. I don't experience any problems when I use the development URL for a CSS file. Does anyone know why this happens?
Here's my code:
$.get("https://rawgit.com/Larpee/The-Khan-Quiz/master/game.js", function (game) {
var sketchProc = function (processingInstance) {
with (processingInstance) {
size(400, 400);
frameRate(30);
eval(game);
}
};
var canvas = document.getElementById("game");
var processingInstance = new Processing(canvas, sketchProc);
});
Update: I think the problem occurs because GitHub (not Rawgit), serves the files as .txt files, while RawGit serves them as .js.
I would still like to receive an explanation for why getting my JavaScript files with a .js extension isn't working, though
For RawGit, you get content-type: application/javascript;charset=utf-8 as expected, and GitHub gives Content-Type: text/plain; charset=utf-8. That seems to be the only difference.
I checked your example and found that when using RawGit (and getting a script response), the success callback wouldn't execute at all, but using GitHub it would (adding a console.log('foo'); statement, for example. I also found that eval() run on your script throws an exception:
Uncaught ReferenceError: createFont is not defined
I made a repo myself with a placeholder JS file that was syntactically correct, in which case success callbacks for $.get() on both RawGit and GitHub did execute, and later added a reference to an undefined name, which caused the call to the RawGit URL fail to execute its callback.
The lesson? When you get a script with $.get(), it is actually immediately executed, and if that eval() fails then everything ends there, silently. This is supported by jQuery getScript load vs execution, which also implies that this (in my opinion) kind of crazy way of dealing with script data ended in version 2.1.0.
Which leads me to suggest that, apart from fixing your script, you should either use $.getScript() (not sure if you have to ensure the result header has application/javascript), or explicitly insert a script element with JS and have an onload callback:
(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.onload = function(){
// remote script has loaded
};
script.src = '[RawGit URL]';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
Additionally, the with block you use should become:
var sketchProc = function (processing) {
processing.size(400, 400);
processing.frameRate(30);
}
var canvas = $('#game'); // use jQuery since you have it
var processingInstance = new Processing(canvas, sketchProc);
// game code now manipulates `processingInstance`
// either directly in scope (or even better as object with parameter)
processingInstance.draw = function () {
var processing = this;
// if your code originally used `processing` throughout,
// do this so that it refers to the specific instance you've created
// ...
}
processingInstance.loop();
// if initialized without a `.draw()` method like above, you need to start the loop manually once there is one
The Processing.js documentation has a lot of examples that are basically in Java and require small modifications to properly deal with JS scope. Sad!

files not loading correctly

Good afternoon everyone! I have searched the web to resolve this problem and tried to implement what I could see as the solution, but I still occasionally run into problems...
The project is modular in design with each module having a .html, .js, and .css file. When loading a module, those associated files are checked for and if they already exist in the DOM (e.g. the module has been opened at least once already), then there are no problems. If the files aren't already loaded (e.g. the module hasn't been loaded yet), then occasionally I run into a problem where a javascript function is called, but the external .js file hasn't been loaded yet. Here's the below function responsible for handling this:
function loadFile(sType,sURI,sCallback) {
// sType the type of file to load: link, script
// sURI the URI of the file to load
// sCallback the code to execute after successfully loading the file
var ref = document.createElement(sType);
if (sType == 'script') {
ref.setAttribute("type","text/javascript");
ref.setAttribute("src",sURI);
} else if (sType == 'link') {
ref.setAttribute("rel","stylesheet");
ref.setAttribute("type","text/css");
ref.setAttribute("href",sURI);
}
ref.async = true;
ref.onreadystatechange = ref.onload = function() {
var state = ref.readyState;
if (! sCallback.done && (! state || /loaded|complete/.test(state))) {
sCallback.done = true;
if (typeof(sCallback) === 'function') {
callback();
} else {
eval(sCallback);
}
}
};
document.getElementsByTagName('head')[0].appendChild(ref);
}
There are several other SO articles that were used for the above function:
Dynamically load external javascript file, and wait for it to load - without using JQuery
Javascript check if function exists
So the above function will be called like:
loadFile('link',"module.css?cache=0", $("#divModule").hide().load("module.php?action=init").fadeIn('slow'));
loadFile('script',"module.js?cache=0", "initModule('req')");
The first call will load the .html file contents (via the module.php call) for the module after the .css file has downloaded. The second call will call the modules js init function after the .js file has downloaded.
It doesn't appear to have any issues with the .css file, but sometimes the module will not load correctly meaning that the layout is rendered correctly, but no values populate (which is what happens with the modules js init function). If I check the 'Web console' in FF, there aren't any errors that are thrown. Any thoughts?
Thanks,
Dave
Hard to say for me w/o seeing what's happening in that module.php code, but it looks to me like your first one at least is firing immediately, rather than as a callback. Unless I'm missing something, the callback should be a function, while right now you're actually executing the jquery hide/load stuff right when you call loadfile. You might want to wrap it in a function.

Can I tell Javascript to call a method from another JS file?

In AppMenu.js,
AppMenu = function()
{
var scope = this;
}
Also noted:
Star.Bus.addEvent("AppMenu_StatSheet");
Star.Bus.on("AppMenu_StatSheet", scope.AppMenu_StatSheet, scope);
scope.registerApp("Exit Game", "AppMenu/images/exit_button.png", "AppMenu_exit", "");
Further down is a method
scope.AppMenu_StatSheet = function()
{
showStats();
}
I moved the location of the showStats() method to another js file, and I want the method to send its call there instead of where it originally was going. In Javascript, can I tell the program where to look to call showStats()?
EDIT Curiously, there is no AppMenu.html. I now believe that all of the html is dealt with by a main HTML file in the above folder.
If you include both Javascript files in your PHP/HTML page, the compiler automatically uses your showStats() function, even when it is called from file1.js and the actual function is located in file2.js.
As long as you include both files in your HTML page you'll be fine. Maybe load the file with showStats() before the other one.

Categories