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
Related
I have a JavaScript function that runs in an HTML file, but in order to avoid "angular is not defined", I put the following before my HTML script
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js">
Is there a way to do this in a actual JavaScript file? I want to write my function in a JavaScript file not HTML so I can't use src HTML code.
I tried copying all the code and putting it in a file and referencing the file in the JavaScript but it doesn't work.
Any workarounds?
A simple technique that I use to load dependencies is to dynamically append them to the document head and use a load EventListener to run my code after the external script has finished loading.
let s = document.createElement('script');
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js';
s.addEventListener('load', init);
document.head.appendChild(s);
function init() {
// your code here
}
Source: I build a lot of plugins/widgets.
There are a variety of solutions to this problem and you should review how scripts load and the onready events for an html document. One simple solution would be coding your custom function to be called in an approach something like this:
<script onload="myCustomFunction();"
src ="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js" >
</script>`
Of course, there are really many different approaches and I would consider this one only to use in a quick and dirty situation.
Something like:
const libname = require("https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js")
Should import the .js file into your project.
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.
This question already has answers here:
How do I include a JavaScript file in another JavaScript file?
(70 answers)
Closed 6 years ago.
I have a bunch of JavaScript links at the bottom of one of my HTML template. I want to create a separate JavaScript file that will only contain all the source links in it.
So instead of cluttering my template footer I want all the links in one JavaScript file. How can I achieve that?
What I'm really asking is how I can get a similar effect as the CSS #import functionality for JavaScript.
And if that is not possible can I place a block of HTML at the footer of my template from a different HTML file?
You could do this with ajax but an easy way is to just append them with jquery
$('.div').append('<script src="myscript.js"></script>');
hope that helps
You can create a seperate js file and a object in it. This object can have multiple keys and their value will these links. Return this object from the file
Hope this snippet will be useful
linkFile.js
var AllLinks = function(){
var _links ={};
_links.keyOne ="link1";
_links.keyTwo ="link2";
return {
links:_links
}
}
Also include this file using script tag
In other file you can retrieve this value as
AllLinks.links.keyOne & so on
Have an array that holds the link to your script files and then you have two options either to use $.getScript() to load each one Or by building an HTML out of it and appending it to your head or body tag. I prefer head tag to keep all the scripts and css files.
Your array of script files
var JsFiles = ["script1.js","script2.js","script3.js","script4.js"];
First approach using $.getScript()
JsFiles.each(function(i,v){
$.getScript(JsFiles[i], function( data, textStatus, jqxhr){
console.log( textStatus ); // Success
});
});
Disadvantage of the above approach is that the getScript makes a async calls to your script files that means if the script2.js is dependent on the script1.js (for example if script1.js is some plugin file which use initialize in script2.js) Then you will face issues.
To overcome you might have to then use Promises or write a callback on each getScript success function which will trigger next script load and so on..
If the order of the script loading is not important then above approach is good to go.
Second approach by building HTML
var scriptTags ="";
JsFiles.each(function(i,v){
scriptTags += "<script src='"+ JsFiles[i] +"'></script>";
});
$('head').append(scriptTags);
Good thing about this approach is that the script files will now load synchronously and you will not face the dependency problem. But make sure the independent files start from first and the dependent files come at last.
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.
I am downloading the JS file asynchronously by appending the JS file to HTML head.
Now in html body, before using the JS file, I want to check if JS file has downloaded and is present in the cache.
If the JS file is NOT present in the cache(e.g: in case of slow internet connnections), I want to block until it is downloaded.
In other words, if JS download is not complete, i want to simulate the behavior as in the case of blocking JS download.
Any idea how this can be achieved?
you can instantiate any object in JS file and in the HTML file you can check if that object is available using typeOf operator so if typeof(x) is undefined you can assume that file is not yet downloaded
Get the JS synchronously instead. Just append a script tag to html > head with src="<script-location>" and the browser will do this download synchronously.
going on a tanget here:
It is poor user-experience to block until something has downloaded. If you write your code using principles of graceful degradation, your page should only activate functionality that is available. Would you let another web-developer subject you to this. No I wouldn't - I would close that tab and move on :)
If you have control over the HTMl file and the JS file: define a "callback" function somewhere in the already-loaded code, and call it from the end of your JS file. Example function:
<html>
<head>
<script>
function notify_file_is_loaded(identifier) {
if (identifier === 'somefile.js') {
// it's loaded!
// run the code that (in synchronous mode) you'd block for
}
}
</script>
<!--- ... --->
and the JS file:
// somefile.js
// some JS code goes here
// ...snip...
notify_file_is_loaded('somefile.js');
Are you deferring the loading of the JavaScript file via JavaScript? If so you should be able to use the onload event handler to execute your code after the JavaScript file has been loaded:
<script>
var js = document.createElement('script');
js.onload = function() {
// your code goes in here
}
js.src = 'foo.js';
document.body.appendChild(js);
</script>