I have a website that I want to work online and offline. I want to decrease load time, so I minified the slow loading scripts. It didn't work enough. Locally, some of the scripts are taking 4-6 seconds to load.
I know that linking scripts externally speeds it up drastically. I have tried it and it works. But some of the users will not have internet access. Is there a way to link a group of scripts to an external site, and locally if they do not have internet access?
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="ui/jquery-ui.min.js" type="text/javascript"></script>
You can do something similar to this answer. Basically, the idea is that you attempt to load the Internet based script for jQuery. Afterward, you do a normal script where you check if jQuery === undefined. If it does, you want to load the local copy.
Basically, an example of what you want to do:
<script src="[jQueryURL]" type="text/javascript"></script>
<script src="[dataTablesURL]" type="text/javascript"></script>
<script src="[jQueryUIURL]" type="text/javascript"></script>
<script type="text/javascript">
if(jQuery === undefined) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "js/jquery-1.9.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
//repeat for other two scripts here
}
</script>
What will happen is that it will attempt to load the scripts in question, and afterward it will check if jQuery is defined. If it's not, that means the scripts didn't load, so you want to load the local versions and append them to your header.
Ensure that the script declares a global variable you can test for. Then generate a local script loading element if the external script fails to load (which you can determine by testing for that variable).
<script src="http://example.com/example.js"></script>
<script>
if !(window.Example) {
document.write('<script src="../scripts/example.js"><\/script>');
}
</script>
<script type="text/javascript">
if(navigator.onLine)
{
alert("Connected");
}
else
{
alert("Not Connected");
}
</script>
First Check if internet connection exist then load external file other wise load internal file
Related
I have an external JavaScript src which I want to add a loading animation until it's finish loading:
<script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
I'm currently using jQuery (window).load, but its waiting until all page is fully loaded, I want to wait only for that specific code:
<script>$(window).load(function(){$(".loadingif").hide();});</script>
Update:
This is my code as you have suggested, it's is not working, what I'm doing wrong---
some text.....
<span class="loading-gif"></span>
<script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
<script>hideLoading();</script>
some text.....
<script>function hideLoading(){$(".loading-gif").hide();}</script>
Hopefully this works:
<script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
<script type="text/javascript">
hideLoadingThingy();
</script>
The second script should run after the first one finishes loading. This is because it is included after the first one, so the first one is loaded first.
Unless the methods in xxx.js are called asynchronously, your browser will only execute one task at a time. Read more about that here
Update:
Use this:
some text 2.....
<span class="loading-gif"></span>
<script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
<script type="text/javascript">$(".loading-gif").hide();</script>
some text 2.....
You could key off of the expected javascript object that will be loaded into global scope:
(function checkValue(){
if (libraryValue === undefined){
setTimeout(checkValue, 100);
} else {
$(".loadingif").hide();
}
})();
I would use Feathercrown's solution unless you choose to load that library asynchronously.
So lets say you're implementing a website that uses jQuery HEAVILY. You could put some code like
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
and import it from some repository. If you're developing it without internet you could download the source and store it somewhere locally, then access it with some script like
<script src="js/jquery-1.10.2.min.js"></script>
But is there a simple way to have both? Such as if you can reach the repository use that, but if you can't use the local copy.
Check for a variable in the first script. If it is not found, use document.write to create the second script tag. Here is an example for jQuery I found here:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="js/jquery-1.7.1.min.js"><\/script>')</script>
The fail-safe way of referencing scripts on a CDN is to link to the local copy only if the CDN has failed for any reason.
The way to do this is simply to check if anything within the script has executed. For jQuery this is simply checking whether jQuery exists:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
if (!window.jQuery) document.write('<script type="text/javascript" src="/path/to/jquery-ver.sion.min.js"><\/script>');
</script>
Personally I have never had a script fail due to a CDN being offline, however I have had periods of internet outage. With scripts set up with a proper fallback, I've been able to continue local development as the pages still work without needing to connect to a CDN.
You can add resources dynamically if required one is not available. for eg:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
if( typeof $ != "function")
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'js/jquery-1.10.2.min.js';
head.appendChild(script);
}
</script>
</head>
<body>
</body>
</html>
Though JQuery hosted on Google CDN should be safe enough, the codes below can be used as a fallback with requireJS.
requirejs.config({
enforceDefine: true,
paths: {
jquery: [
'//ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js',
'js/jquery-ui.min.js'
]
}
});
require(['jquery'], function ($) {
});
Let's say I have a bunch of scripts on my server, which are used in my app.
So, my <head> contains a bunch of
<script src="http://myServer.com/myScript.js"></script>
If I am developing on localhost & don't have net access, I would like to reference those as a bunch of
<script src="http://localhost/myScript.js"></script> or, even,
<script src="myScript.js"></script>
I am very new to JS, is there a standard way to switch between two possible servers for the script file? Google is not my friend on this matter.
You could just dynamically load the script and add it to the document, based on whether you're accessing the page from localhost or not, as such:
<script>
var script = document.createElement("script");
if (/localhost/.test(document.location.hostname)) {
script.setAttribute("src", "./myScript.js");
} else {
script.setAttribute("src", "http://www.myServer.com/myScript.js");
}
document.body.appendChild(script);
</script>
In situations where I'd like to be able to continue development while offline on a webapp that has resources pulled from CDNs, I've used fallbacks.
For example, for jQuery:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
if(!window.jQuery) {
document.write('<script src="./js/jquery.min.js"><\/script>');
console.error('jQuery from CDN not available - reverting to local copy');
}
</script>
Or for BootstrapJS:
<script type="text/javascript" src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
<script type="text/javascript">
if(!(typeof $().modal == 'function')) {
document.write('<script src="./js/bootstrap.min.js"><\/script>');
console.error('Bootstrap JS from CDN not available - reverting to local copy');
}
</script>
Or for FontAwesome:
<link type="text/css" rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" />
...
<span class="fa hide" id="faChecker"></span>
<script type="text/javascript">
if($('#faChecker').css('fontFamily') !== 'FontAwesome') {
$('<link type="text/css" rel="stylesheet" href="./css/font-awesome.min.css" \/>').appendTo('head');
console.error('FontAwesome CSS from CDN not available - reverting to local copy');
}
</script>
Similarly, you can make use of some variable that myScript.js would set and if it's not set, use the local fallback version.
This has the added benefit of helping prevent your site from malfunctioning if a CDN goes down.
I have an HTML file like this:
<html>
<head>
<title>World Aviation</title>
<script language="javascript" src="./jquery-min.js"> </script>
<script language="javascript" src="./jsDraw2D.js"> </script>
<script language="javascript" src="./script.js"> </script>
</head>
<body>
<input onClick="startAnimBackground();" type="button" value="Start"/>
<script language="javascript">
initAirports();
initRoutes();
var w;
function startAnimBackground()
{
if(typeof(Worker) !== "undefined")
{
if(typeof(w) == "undefined")
{
w = new Worker("start_script.js");
}
} else {
startAnimation();
}
}
</script>
</body>
</html>
the file "start_script.js" contains only 1 line which calls the startAnimation() function. This function is located in "script.js"
My problem is: my browser supports web-workers, so it creates a web-worker and loads the file "start_script.js", but it fails to call the function "startAnimation()" indicating that it cannot find the function. But this function is located in script.js which is included in the head section. So, the only conclusion I can draw is that web-worker JS files have a different scope and thus is not able to include the 3 javascript files specified in the head section. So what should I do to make this work?
Thanks.
Web workers don't share functions, variables, or scripts with the main script.
To load dependencies, call importScripts() in your worker.
To allow your web worker to interact with or affect the main script or the DOM, you have to use message passing and have the main script listen for, interpret, and act on the messages.
See: https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers
I'm trying to check if jQuery is loaded. If not, load it, then proceed to load external javascript files. The issue I'm having is one of the external files expects to have jQuery already loaded, so I get a 'jQuery not defined" error. Is there a way I can load jQuery using JavaScript, and as soon as it's done then continue?
if(!window.jQuery){
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
//load these scripts after jquery has been loaded
<script src="/some/other/js/file/that/requires/jquery"></script>
<script src="/some/other/js/file/that/requires/jquery"></script>
What I'd like to do is wait for this to completely load before continuing. I tried this but I got errors about exceeding call stack
Consider the technique tried and tested by HTML5Boilerplate instead:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
Note that <script src="//ajax.googleapis.com only works on an actual http: or https: server; if you're testing on a local filesystem, write <script src="http://ajax.googleapis.com instead.