Force load JS script on page - javascript

I have a third party JS script with class Oreole defined there. This script is located on a CDN server elsewhere. I have this reference in my HTML:
<script src="https://someothercdn.com/oreole.js"/>
Later in my page script code I have
let oreole = new Oreole
Sometimes the CDN fails with 504 or 502 and my code crashes. Usually, page reload helps. But how do I force script reload on my page?
if (typeof(Oreole) == "undefined") {
//Do what exactly?
}

You should probably host oreole.js somewhere else, but if you want to go with unreliable cdn, you can do something like this using jquery
$.getScript("https://someothercdn.com/oreole.js", function() {
// do everything that needs oreole.js here
});
The page will keep running atleast, if oreole.js is not found or something happens only oreole part will crash

Related

How to load javascript that does not block rendering?? How to load after full page has been painted?

I am loading the chat service called drift. I am getting very bad score on PageSpeed mobile because of this only. I want to load it so it does not block rendering and like should start after whole page is painted.
If you want to consider the website here it is:
https://stockarea-application-test.herokuapp.com
I have tried to use async and defer to load the javascript file but both of them are blocking the render. ( I checked that thing over pagespeed insights recommendation).
I also have used jquery $.getScript() after document ready function but still its showing render blocking
Please I really need some help on how I could solve it. Some things on internet says about worker files but they don't have DOM apis on them so can't use them as this drift service do paint somethings on DOM. so please help
I think what you tried is only let the script load asynchronously, but because processing the script must be in the only main thread, the only way not to block your business code is putting the third-party script in a frame if it can be. ( or wait a long timeout and execute the code quietly)
You can use async and defer method with jQuery. But better than async and defer attributes, in this way you can load javascript after the browser has finished loading resources on the page.
When the browser has finished loading resources on the page, it fires the load event. And you can tell the browser to wait to load scripts until that happens.
Here's how to do that with jQuery :
$(window).on("load", function() {
$("body").append("<script type='text/javascript' src='some-javascript.js'>") //Load js after rendered
});
You can also do with native javascript :
window.addEventListener("load", function(){
const script = document.createElement("script")
script.src = "some-javascript.js" //Load js after rendered
document.body.appendChild(script)
});
In this way, it creates the script element after the resources have been loaded.

How to redirect page after "Enable Unsafe Scripts" is enabled?

I have a website that requires "Load Unsafe Scripts" to be enabled to load. What I want is the site to redirect to another after the user enables the "Load Unsafe Scripts" option is enabled. I can work with HTML, and JavaScript. Any help would be appreciated!
As already mentioned, you really should focus on fixing the unsafe script by serving everything (or nothing) from HTTPS.
If you absolutely can't for some reason, and for the sake of exercise: there is no trigger that you can directly react to when this occurs.
Your only real option would be to periodically try to add the script again if it hasn't been already. This wouldn't involve a redirect, but just pulling the script(s) in again.
Something like this:
function loadUnsafe() {
if (!somethingInYourScript) {
const script = document.createElement('script');
script.src = 'https://path.to/my-script.js';
document.appendChild(script);
setTimeout(loadUnsafe, 10000); // wait 10 seconds to try again
}
}
loadUnsafe();
This will try to pull in your script every 10 seconds if somethingInYourScript doesn't exist. Once it does exist, it'll stop.
The somethingInYourScript would be something that the script pulls in (for example, if you were trying to bring in jQuery, you could check if jQuery variable exists because it will once the script is loaded.
You could try to pull in the main file you want (if your site can handle that), or you could try to pull in an unsafe script that would cause a redirect/refresh.
You can load a script from an unsave source which redirect to the other page.
Something like
var locationn = "https://google.com";
window.location = locationn;
But you realy need to make your scripts save...

Javascript in asp.net MVC... Beginner issue

I created an Asp.Net MVC Internet Aplication and in my Index view of the Home Controller I have this
This is the first line, before the script results.
<script type="text/javascript" src="~/Script/Teste.js"></script>
<br />
This line comes after the script.
In my Teste.js I have this:
document.write("Yes! I am now a JavaScript coder!");
But nothing happens. If I change the src attribute and put some random name src="aaaa", despite the fact "aaaa" doesnt exist, I get no error in runtime.
EDIT
Also, check your path again. The default MVC templates in VS create a folder called Scripts, not Script. ("~/Scripts/teste.js")
Per the comment below, this was not the root cause of the issue, but in other cases can easily bite new JavaScript developers.
Most likely, your document.write function is firing before the document is ready, leading to the appearance that nothing is happening. Try the following in your Teste.js file
window.onload = function ()
{
document.write("Yes! I am now a JavaScript coder!");
//or even better as a test
alert("This alert was called");
}
Check the source of your page as well, it could be the document is being written to, you just can't see it due to markup/page styling.
As for you second issue, there will be no 'Runtime Exception' thrown if you reference a non-existent file. If you are using tools like Firebug or Chrome's developer tools, you should see a request to http://siteDomain/Scripts/aaaa.js with a response of 404, not found.
You generally should avoid using document.write() unless you absolutely have to use it for some reason... I don't think I've ever come across such a situation, and write a lot of Javascript.
Try this:
1) Put this in your HTML:
<script src="/scripts/teste.js"></script>
2) Put this in your JS:
alert('Yes! I am now a JavaScript coder!');
3) Open Chrome since it makes it easy to look for external resources loading and open the Network tab in Developer Tools (click the menu button at top-right, Tools > Developer Tools, Network tab).
4) Run your project and copy/paste the URL in the browser that comes up into this Chrome window, and hit enter.
When your page loads one of 2 things will happen:
A) You'll get the alert box you wanted or
B) You'll find out why it isn't loading because the Network tab will show the browser attempting to fetch teste.js and failing in some fashion, for example a 404, which would indicate you've got a typo in the path, or the script isn't where you thought it was, etc.
Put the following line at the very end of your document. There should not be anything after. Then try to load the page.
<script type="text/javascript" src="~/Script/Teste.js"></script>
Also, try pressing F12 once the page loads to see the source. Check if you script is there.
In MVC, the tilde is used to refer to the root URL of your application. However, it cannot normally parse this information. If you write:
<script src="~/Script/Teste.js"></script>
The lookup will fail, because the ~ means nothing special in HTML. If you're using Razor as your view engine (not ASPX), you need to wrap that call in Url.Content like so:
<script src="#Url.Content(~/Script/Teste.js)"></script>
Doing this will ensure a valid URL is provided to the browser.
With that in mind, you need to check that you have the file name and folder name both correct. You also need to ensure that the file is being deployed with your application. You can do this my opening the properties panel while the file is selected in the Solution Explorer and pressing F4.

forcing page load on an AJAX-loaded page

I have an issue with an third-party integration on an iPad-specific website, which has a number of pages loaded via AJAX.
When I go to the page for the first time the functionality that is expected to be available is not, and only when I do a page refresh in Safari do I see the feature.
In the 3rd party JavaScript there is this sort of code peppered throughout:
script.onload = script.onreadystatechange = function () { // do something }
Here is the full JavaScript included file.
Is there a way that I can either force a page load on the iPad or build in some workaround that means that when I change to the page where the JavaScript is included and fires?
As I mentioned, this is only apparent on an iPad-specific website and the same feature has no problem on a desktop browser where the page is not loaded via AJAX.
i believe web servers allow you to add content dynamically for all pages rendered using the web server. which allows you to insert a code snippet which can ideally check if its a ipad website and do page load as you requested.
follow the below thread
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/e27f918e-89a9-45a8-8604-2ad2ded09d64.mspx?mfr=true
I have no idea what your code looks like, but, having experienced the same issues repeatedly with jQuery, I would suggest you manually call the initialize function of the 3rd party script within a window ready state function:
$(window).ready(function(e) {
// function that initializes the 3rd party script gets called here.
});

External Javascript Timeout

I have a number of tracking scripts and web services installed on my website and I noticed when one of the services goes down, it still tries to call the external javascript file hosted on a different server. In Firefox, Chrome and other new browsers, there doesn't seem to be any issues when one of the services go down. However, in IE7 and IE8, my pages don't load all the way and time out before everything is displayed. Is there any way to add a time out on these javascript calls to prevent them from breaking my pages when they go down?
You can load them dynamically after page load with JS. If the JS files are on a different server, the browser will still show a "browser busy" indicator when you do that, but the original page will load.
If you can fetch the JS from your own site, you can load it with XMLHttpRequest after page load (or with your favorite JS library's helpers, e.g. jQuery's $.ajax(...)) and then eval it. This way the fetching itself won't show the browser-busy indicator.
To fetch the JS from your own site, you can download it from your tracking provider (which won't be officially supported but usually works) - just remember to refetch new versions every once in a while - or you can create a "forwarding" service on your own site that fetches it from the tracking provider and caches it locally for a while. This way your JS won't be in danger of staleness.
Steve Souders has more information about deferred loading of scripts and browser-busy indicators.
Try adding defer="defer"
The defer attribute gives a hint to
the browser that the script does not
create any content so the browser can
optionally defer interpreting the
script. This can improve performance
by delaying execution of scripts until
after the body content is parsed and
rendered.
Edit
This will prevent those scripts from running until the page loads:
function loadjs(filename) {
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
}
window.onLoad = function() {
loadJs("http://path.to.js");
loadJs("http://path.to2.js");
...
}
If you need to load external scripts and you want to enforce a timeout limit, to avoid having a busy indicator running for too long, you can use setTimeout() with window.stop() and, the IE equivalent:
http://forums.devshed.com/html-programming-1/does-window-stop-work-in-ie-1311.html
var abort_load = function() {
if(navigator.appName == "Microsoft Internet Explorer") {
window.document.execCommand('Stop');
} else {
window.stop();
}
};
/**
* Ensure browser gives up trying to load JS after 3 seconds.
*/
setTimeout(abort_load, 3000);
Note that window.stop() is the equivalent of the user clicking the stop button on their browser. So typically you'd only want to call setTimeout() after page load, to ensure you don't interrupt the browser while it's still downloading images, css and so on.
This should be combined with the suggestions made by orip, namely to load the scripts dynamically, in order to avoid the worst case of a server that never responds, resulting in a "browser busy" indicator that's active until the browser's timeout (which is often over a minute). With window.stop() in a timer, you effectively specify how long the browser can try to load the script.
Also note that setTimeout()'s interval is not that precisely interpreted by browsers so round up in terms of how much time you want to allow to load a script.
Also, one counter-indication to using window.stop() is if your page does things like scroll to a certain position via js. You might be willing to live with that but in any case you can make the stop() conditional on NOT having already loaded the content you expected. For example if your external JS will define a variable foo, you could do:
var abort_load = function() {
if (typeof(foo) == "undefined") {
if(navigator.appName == "Microsoft Internet Explorer") {
window.document.execCommand('Stop');
} else {
window.stop();
}
}
};
This way, in the happy path case (scripts do load within timeout interval), you don't actually invoke window.stop().

Categories

Resources