How to block if JS download is not completed - javascript

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>

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 can I import this in JavaScript?

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.

External JS file can't be executed

I have a js function that should get some advertisement js code from some server and place it in specified DOM element. It looks like this:
function LoadAd(scriptContainer)
{
var js = document.createElement("script");
js.async = true;
js.src ='someAdUrl';
var sHolder = document.getElementById(scriptContainer);
if (sHolder != null) {
sHolder.appendChild(js);
}
}
the argument 'scriptContainer' is an ID of DOM element, that should contain created js element.
This external js file contains a lot of code that should provide an ad. But this code is never reached and never executed.
When I put this js src directly in html:
<script src='someAdUrl'></script>
it works fine.
I've checked, the js file is being loaded.
Any ideas?
EDIT: Here is an example of content of js file:
document.write('<!-- Some Message -->\n\n\n<img width=\"336\" height=\"110\" border=\"0\" src="someImageSource">\n\n');
And it always contains document.write
If the external JS file is being loaded, have you checked whether or not the function is actually being invoked and run?
If the function isn't self-executing and you don't explicitly call it, the code won't run.
I use this code in my case. It may help you
var js=document.createElement('script');
js.setAttribute('src','http://domain.com/js/jscpt.js');
document.body.appendChild(js);

Can an external Javascript file be called and executed depending on a conditional?

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");
}

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