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.
Related
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.
I'm playing around with Google Drive API, and noticed that they are calling a handleClientLoad function onload of the client.js.
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
Trying to avoid creating globals, I thought I would start with creating another js file, that would contain a module pattern and return handleClientLoad.
var module = (function (window, $) {
'use strict';
var module = {
handleClientLoad: function () {
console.log('ok, can access');
}
};
return module;
}(window, jQuery));
And then I assumed I could just call the handleClientLoad by doing module.handleClientLoad, but that doesn't seem to be working.
<script src="scripts/main.js"></script>
<script src="https://apis.google.com/js/client.js?onload=module.handleClientLoad"></script>
Questions:
Is it possible to call the module.handleClientLoad from onload of client.js?
Appending onload and calling a function from a script file seems sloppy and obtrusive, no? Is there a cleaner way to know when the client.js has loaded?
Have you tried debugger, and are you sure module. hanfleClientLoad exists at the time the callback is fired?
You can poll for the existence of gapi.client as a global object. Give it a few milliseconds to initialise before invoking its methods.
I found that jQuery.getScript() worked quite nicely for this. Documentation here.
Instead including the <script> tag in the html page, I simply included the following line in my js file:
jQuery.getScript( "https://apis.google.com/js/api.js", handleClientLoad );
It might require slight tweaking for the way you structured your module, but I think this will be easier than passing a parameter to your <script> tag (at least I found it easier).
I know this is old, but I was messing around with this because this was related to a question on a test I was studying for. You can use onload like this when you call the script:
<script src="https://apis.google.com/js/client.js" onload="handleClientLoad()"></script>
For anyone wanting to know why this won't work:
<script src="https://apis.google.com/js/client.js">handleClientLoad()</script>
It's because any code between a script tag with "src=" in it will be ignored.
And I'm not sure why using onload= in the script tag calling the external script is any more obtuse than appending ?onload=module.handleClientLoad to the source? But that's just me.
In the end, I'm not sure why exactly this was a question on the test, because based on searching, this doesn't seem to be a common thing that anyone does.
I know that I can run an external Javascript file from within HTML with the following syntax:
<script type="text/javascript"
src="http://somesite.com/location/of/javascript.js">
</script>
This will result in http://somesite.com/location/of/javascript.js being run the moment the browser reads that line of the HTML.
But is there a way I can run an external Javascript file from within Javascript? Something like:
if (x == 1)
{
run this! -> http://somesite.com/location/of/javascript.js;
}
Obviously that's not valid code. But I can't find any example of what might be the right way to do this (if it exists), because all the help text I find with Google searches tell me how to run Javascript from within HTML
I know that I can include a Javascript file and then call functions within it. However, in this situation, I do not have any control over http://somesite.com/location/of/javascript.js, and it is designed to execute the moment it is called. I can't change how it works, so I need to figure out how to call it at the right time in the right way.
Is there a way I can get it to be called and executed immediately depending on a conditional statement?
Yes, in Pure Javascript you can Load javascript dynamically
var s = document.createElement("script");
s.src = "test.js";
document.body.appendChild(s);
There is a way...
var extfile = document.createElement('script')
extfile.setAttribute("type","text/javascript")
extfile.setAttribute("src", external_jsfilename)
document.getElementsByTagName("head")[0].appendChild(extfile)
Simple as that ....
Use jQuery's .getScript() the file will be loaded and then executed
if (x == 1)
{
$.getScript( "http://somesite.com/location/of/javascript.js");
}
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>
Not sure if this is possible or even if I should do it, but I think it's quite interesting.
I have a javascript file which I'm referencing in a flat HTML page. I'd like to pass in a parameter or two via the path to the script. Like this;
<script src="/scripts/myJavascriptFile.js?config1=true" type="text/javascript"></script>
Not really sure if it can work but it would make my solution a little easier for others to take my script and implement (arguable).
Cheers,
Mike
I don't think that passing in variables via the src attribute is possible out of the box without some extra coding on your part (there is an article here if you are interested!). You could do the following though, which should provide the same functionality as you are looking for:
Define your "config" variables in a single script block on your HTML page:
<script type="text/javascript">
var config1 = true;
</script>
Reference your external JS file in a second script block:
<script src="/scripts/myJavascriptFile.js" type="text/javascript"></script>
Add this code to your external JS file to reference the "local" variable in your HTML:
var conf1 = window.config1;
if (conf1) {
// Do stuff
}
This is a variation on Matt's answer. I have a similar case where I need a jQuery file to use a value that is generated in the HTML (by Razor in this case). I write the value to a meta tag, generated as it is from the controller:
<meta name="sessionId" content="#ViewBag.SessionId">
and then read it in the jQuery file:
var sessionId = $("meta[name=sessionId]").attr("content");
It's not quite the same as passing it in by querystring, but useful if that information is considered "meta-information" of the HTML page.