how to load javascript dynamically - javascript

I try to load some js files dynamically,for example:
function openInforWindow(){
//check if the InforWinow.js has been loaded or not
if(window.InforWindow){
//do the right thing
}
else {
loadJs('xxxxxx/InforWindow.js');
// do the right thing
//but here ,the infowindow is not definded yet.
}
}
function loadJs(filename){
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
How to make sure that the vars or functions in the js which is dynamically loaded can be add to the javascript execute environment so I can use them ?

adding a script element isn't a blocking operation, this means that your loadJs method returns immediately when your external script isn't even loaded (nor interpreted). You have to wait for it to load.
function openInforWindow(){
//check if the InforWinow.js has been loaded or not
if(window.InforWindow){
//do the right thing
}
else {
var loadHandler = function() {
//do stuff with inforWindow
};
loadJs('xxxxxx/InforWindow.js', loadHandler);
}
}
function loadJs(filename, handler){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "js");
fileref.onreadystatechange = function () {
if (this.readyState == 'complete')handler();
};
fileref.onload = handler;
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref);
}

One approach could be to load the script using jQuery's AJAX loader. Example below:
function loadJs(filename, functionToCall){
$.getScript(filename, functionToCall);
}
Now, you just need to call loadJs("script.js", callback);, and it will first completely load script.js, and then run callback().

You can dynamically insert a <script/> tag into your document, here is a script that will work in firefox/chrome, you may need a bit of tweaking in IE:
loadJs = function(src) {
var script = document.createElement('SCRIPT');
script.setAttribute('src', src);
document.getElementsByTagName('HEAD')[0].appendChild(script);
}
Then wait for the document.onload event to fire, your window.InforWindow should be loaded at that stage.
document.addEventListener('load', function () {
// Your logic that uses window.InforWindow goes here
}, false);
Note that IE does the load event listener slightly differently:
document.attachEvent('onload', function() {
// Your logic that uses window.InforWindow goes here
});

Related

How to recognize that one js file loaded?

I try to display progress bar when page loading. I want change width of progress bar after js files loaded .At the final after load all documents set with of progress bar to 100% .Now I need to recognize js files loading with javascript.
Is this possible ? Please advice.
For internal js files loading recognition:
As functions and variables can be accessed from another file you can set the value of global progress variable and display it's value by calling the function
//on page or head js file
var progress = 0;
function displayProgress()
{
//show progress based on 'progress' variable
}
//file1.js
progress += 10;
displayProgress();
...
//file2.js
progress += 20;
displayProgress();
...
For external js files there is good article. The main idea is to periodically check existense of external functions (typeof fixpng =='function') and if it exist - stop checking and display progress.
Here's the JavaScript code to load the external library with a
callback passed in:
function loadExtScript(src, callback) { var s = document.createElement('script'); s.src = src; document.body.appendChild(s); // if loaded...call the callback }
Firefox allows you to listen for the onload event on the script
element:
s.onload = callback;
With Internet Explorer you can wait for a state change on the script
element:
s.onreadystatechange = function() { if ( this.readyState != "loaded"
) return; callback.call(); }
The problem comes with Safari - there's no event change for Safari, so
we can't tell when the script has loaded. This is the solution I came
up with (and this solution should also work with Opera):
function loadExtScript(src, test, callback) { var s =
document.createElement('script'); s.src = src;
document.body.appendChild(s);
var callbackTimer = setInterval(function() {
var call = false;
try {
call = test.call();
} catch (e) {}
if (call) {
clearInterval(callbackTimer);
callback.call();
} }, 100); }
The function takes a test as a parameter. Since you are the designer
of the app, you'll know what successful test is. Once this test is
true, it will execute the callback. A simple test could be to check
whether a function exists, for example:
loadExtScript('/fixpng.js', function() { return (typeof fixpng ==
'function'); }, myCallbackFunction);
If you know at least one defined namespace (almost all libraries and plugins have it: e.g. jQuery, jQuery.ui, jQuery.mobile, toastr, DataTable, etc.) or one global variable name introduced by the script files which are being loaded, then you can do this:
(function(undefined) {
var scriptFilesLoaded = false,
files = [],
timer = setInterval(function(){
try {
files = [
jQuery,
jQuery.mobile,
jQuery.ui,
someGlobalVariableName
];
if(files.indexOf(undefined)<0){
scriptFilesLoaded = true;
clearInterval(timer);
}
}
catch(e) {
console.warn('Preloader in action: Script files not loaded yet.');
}
},200);
})();
It doesn't matter if the script file is remote or local.

External JavaScript with jQuery dependence being loaded before jQuery

Externally loading a script, but my script was placed by the client above jQuery (which is a requirement), as such, my script does not work.
I am trying to make my code wait until jQuery has loaded before executing, but I am having difficulty with nested functions within my code; specifically $(x).hover, or $(x).click etc.
I can separate my functions without much trouble, which include jQuery selectors (but they won't be called unless 'x y or z' is done (i.e. until after jQuery is loaded).
I don't know how to have the hover, click etc implemented as they don't work within my $(document).ready(function(){... which is located within the onload yourFunctionName described below - with thanks to user #chaos
Link to onload hook: https://stackoverflow.com/a/807997/1173155
and a quote of the above link:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
yourFunctionName();
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
Thanks in advance for any help with this.
I have also looked into a loop that checks if jQuery is activated before continueing, but did not implement it as I found that JavaScript does not have a sufficient sleep method that sleeps that specific script.
Solution:
if(typeof jQuery === "undefined"){
if(window.attachEvent) {
window.attachEvent('onload', myLoadFunction);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
myLoadFunction();
};
window.onload = newonload;
} else {
window.onload = myLoadFunction;
}
}
}
else {
myLoadFunction();
}

Verify External Script Is Loaded

I'm creating a jquery plugin and I want to verify an external script is loaded. This is for an internal web app and I can keep the script name/location consistent(mysscript.js). This is also an ajaxy plugin that can be called on many times on the page.
If I can verify the script is not loaded I'll load it using:
jQuery.getScript()
How can I verify the script is loaded because I don't want the same script loaded on the page more than once? Is this something that I shouldn't need to worry about due to caching of the script?
Update:
I may not have control over who uses this plugin in our organization and may not be able to enforce that the script is not already on the page with or without a specific ID, but the script name will always be in the same place with the same name. I'm hoping I can use the name of the script to verify it's actually loaded.
If the script creates any variables or functions in the global space you can check for their existance:
External JS (in global scope) --
var myCustomFlag = true;
And to check if this has run:
if (typeof window.myCustomFlag == 'undefined') {
//the flag was not found, so the code has not run
$.getScript('<external JS>');
}
Update
You can check for the existence of the <script> tag in question by selecting all of the <script> elements and checking their src attributes:
//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
return ($(this).attr('src') == '<external JS>');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
$.getScript('<external JS>');
}
Or you can just bake this .filter() functionality right into the selector:
var len = $('script[src="<external JS>"]').length;
Few too many answers on this one, but I feel it's worth adding this solution. It combines a few different answers.
Key points for me were
add an #id tag, so it's easy to find, and not duplicate
Use .onload() to wait until the script has finished loading before using it
mounted() {
// First check if the script already exists on the dom
// by searching for an id
let id = 'googleMaps'
if(document.getElementById(id) === null) {
let script = document.createElement('script')
script.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key=' + apiKey)
script.setAttribute('id', id)
document.body.appendChild(script)
// now wait for it to load...
script.onload = () => {
// script has loaded, you can now use it safely
alert('thank me later')
// ... do something with the newly loaded script
}
}
}
#jasper's answer is totally correct but with modern browsers, a standard Javascript solution could be:
function isScriptLoaded(src)
{
return Boolean(document.querySelector('script[src="' + src + '"]'));
}
UPDATE July 2021:
The accepted solutions above have changed & improved much over time. The scope of my previous answer above was only to detect if the script was inserted in the document to load (and not whether the script has actually finished loading).
To detect if the script has already loaded, I use the following method (in general):
Create a common library function to dynamically load all scripts.
Before loading, it uses the isScriptLoaded(src) function above to check whether the script has already been added (say, by another module).
I use something like the following loadScript() function to load the script that uses callback functions to inform the calling modules if the script finished loading successfully.
I also use additional logic to retry when script loading fails (in case of temporary network issues).
Retry is done by removing the <script> tag from the body and adding it again.
If it still fails to load after configured number of retries, the <script> tag is removed from the body.
I have removed that logic from the following code for simplicity. It should be easy to add.
/**
* Mark/store the script as fully loaded in a global variable.
* #param src URL of the script
*/
function markScriptFullyLoaded(src) {
window.scriptLoadMap[src] = true;
}
/**
* Returns true if the script has been added to the page
* #param src URL of the script
*/
function isScriptAdded(src) {
return Boolean(document.querySelector('script[src="' + src + '"]'));
}
/**
* Returns true if the script has been fully loaded
* #param src URL of the script
*/
function isScriptFullyLoaded(src) {
return src in window.scriptLoadMap && window.scriptLoadMap[src];
}
/**
* Load a script.
* #param src URL of the script
* #param onLoadCallback Callback function when the script is fully loaded
* #param onLoadErrorCallback Callback function when the script fails to load
* #param retryCount How many times retry laoding the script? (Not implimented here. Logic goes into js.onerror function)
*/
function loadScript(src, onLoadCallback, onLoadErrorCallback, retryCount) {
if (!src) return;
// Check if the script is already loaded
if ( isScriptAdded(src) )
{
// If script already loaded successfully, trigger the callback function
if (isScriptFullyLoaded(src)) onLoadCallback();
console.warn("Script already loaded. Skipping: ", src);
return;
}
// Loading the script...
const js = document.createElement('script');
js.setAttribute("async", "");
js.src = src;
js.onload = () => {
markScriptFullyLoaded(src)
// Optional callback on script load
if (onLoadCallback) onLoadCallback();
};
js.onerror = () => {
// Remove the script node (to be able to try again later)
const js2 = document.querySelector('script[src="' + src +'"]');
js2.parentNode.removeChild(js2);
// Optional callback on script load failure
if (onLoadErrorCallback) onLoadErrorCallback();
};
document.head.appendChild(js);
}
This was very simple now that I realize how to do it, thanks to all the answers for leading me to the solution. I had to abandon $.getScript() in order to specify the source of the script...sometimes doing things manually is best.
Solution
//great suggestion #Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length;
if (len === 0) {
alert('script not loaded');
loadScript('Javascript/MyScript.js');
if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
alert('still not loaded');
}
else {
alert('loaded now');
}
}
else {
alert('script loaded');
}
function loadScript(scriptLocationAndName) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
Create the script tag with a specific ID and then check if that ID exists?
Alternatively, loop through script tags checking for the script 'src' and make sure those are not already loaded with the same value as the one you want to avoid ?
Edit: following feedback that a code example would be useful:
(function(){
var desiredSource = 'https://sitename.com/js/script.js';
var scripts = document.getElementsByTagName('script');
var alreadyLoaded = false;
if(scripts.length){
for(var scriptIndex in scripts) {
if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
alreadyLoaded = true;
}
}
}
if(!alreadyLoaded){
// Run your code in this block?
}
})();
As mentioned in the comments (https://stackoverflow.com/users/1358777/alwin-kesler), this may be an alternative (not benchmarked):
(function(){
var desiredSource = 'https://sitename.com/js/script.js';
var scripts = document.getElementsByTagName('script');
var alreadyLoaded = false;
for(var scriptIndex in document.scripts) {
if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
alreadyLoaded = true;
}
}
if(!alreadyLoaded){
// Run your code in this block?
}
})();
Simply check if the global variable is available, if not check again. In order to prevent the maximum callstack being exceeded set a 100ms timeout on the check:
function check_script_loaded(glob_var) {
if(typeof(glob_var) !== 'undefined') {
// do your thing
} else {
setTimeout(function() {
check_script_loaded(glob_var)
}, 100)
}
}
Another way to check an external script is loaded or not, you can use data function of jquery and store a validation flag. Example as :
if(!$("body").data("google-map"))
{
console.log("no js");
$.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initilize",function(){
$("body").data("google-map",true);
},function(){
alert("error while loading script");
});
}
}
else
{
console.log("js already loaded");
}
I think it's better to use window.addEventListener('error') to capture the script load error and try to load it again.
It's useful when we load scripts from a CDN server. If we can't load script from the CDN, we can load it from our server.
window.addEventListener('error', function(e) {
if (e.target.nodeName === 'SCRIPT') {
var scriptTag = document.createElement('script');
scriptTag.src = e.target.src.replace('https://static.cdn.com/', '/our-server/static/');
document.head.appendChild(scriptTag);
}
}, true);
Merging several answers from above into an easy to use function
function GetScriptIfNotLoaded(scriptLocationAndName)
{
var len = $('script[src*="' + scriptLocationAndName +'"]').length;
//script already loaded!
if (len > 0)
return;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
My idead is to listen the error log if there is an error on script loading.
const checkSegmentBlocked = (e) => {
if (e.target.nodeName === 'SCRIPT' && e.target.src.includes('analytics.min.js')) {
window.isSegmentBlocked = true;
e.target.removeEventListener(e.type, checkSegmentBlocked);
}
};
window.addEventListener('error', checkSegmentBlocked, true);
Some answers on this page are wrong. They check for the existence of the <script> tag - but that is not enough. That tells you that the tag was inserted into the DOM, not that the script is finished loading.
I assume from the question that there are two parts: the code that inserts the script, and the code that checks whether the script has loaded.
The code that dynamically inserts the script:
let tag = document.createElement('script');
tag.type = 'text/javascript';
tag.id = 'foo';
tag.src = 'https://cdn.example.com/foo.min.js';
tag.onload = () => tag.setAttribute('data-loaded', true); // magic sauce
document.body.appendChild(tag);
Some other code, that checks whether the script has loaded:
let script = document.getElementById('foo');
let isLoaded = script && script.getAttribute('data-loaded') === 'true';
console.log(isLoaded); // true
If the both of those things (inserting and checking) are in the same code block, then you could simplify the above:
tag.onload = () => console.log('loaded');
I found a quick tip before you start diving into code that might save a bit of time. Check devtools on the webpage and click on the network tab. The js scripts are shown if they are loaded as a 200 response from the server.

How can I check if the DOM is ready without a listener?

If I have a script that is loaded dynamically, I want it to wait until the DOM is ready before executing code. However, if the script loads too slowly, the DOM will already be ready and therefore the DOM-Ready function will not run.
No frameworks, please, I'm relying on pure JavaScript.
Thanks in advance!
Without a listener there's no 100% reliable way to ensure that the entire DOM is loaded. You can do something like this:
var myChecker = setInterval(function () {
var checkElem = document.getElementById('myRefElement');
if (checkElem != null) {
clearInterval(myChecker);
myFunction();
}
}, 100);
That'll wait until some target element you care about exists.
Part way down on this page: http://dean.edwards.name/weblog/2006/06/again/ you will find this code, which is what I use to do what you are asking about:
I leave the comment with the code as I didn't write it:
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*#end #*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
Very simple - put your script immediately before the closing body tag (if you have one). It doesn't guarantee that the DOM is ready, but it's more reliable that DOM ready listeners and runs earlier than load listeners.
Here are a couple of pure javascript domready events:
http://snipplr.com/view/6029/domreadyjs/
http://www.geekdaily.net/2007/07/27/javascript-windowonload-is-bad-mkay/
snippet that checks the document.readyState
http://www.dustindiaz.com/smallest-domready-ever

Why does jQuery load twice in my GreaseMonkey Script

for some reason my Firefox4+GreaseMonkey Script loads jQuery twice. I copy'n'pasted the following snippet, the "test" alert shows twice.
Regards
var $;
// Add jQuery
(function(){
if (typeof unsafeWindow.jQuery == 'undefined') {
var GM_Head = document.getElementsByTagName('head')[0] || document.documentElement,
GM_JQ = document.createElement('script');
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
GM_JQ.type = 'text/javascript';
GM_JQ.async = true;
GM_Head.insertBefore(GM_JQ, GM_Head.firstChild);
}
GM_wait();
})();
// Check if jQuery's loaded
function GM_wait() {
if (typeof unsafeWindow.jQuery == 'undefined') {
window.setTimeout(GM_wait, 100);
} else {
$ = unsafeWindow.jQuery.noConflict(true);
letsJQuery();
}
}
// All your GM code must be inside this function
function letsJQuery() {
alert("test");
}
This is probably because the target page is loading frames or iframes.
Add these lines to the top of the code-portion of your script:
if (window.top != window.self) //-- Don't run on frames or iframes
return;
Also, if you are just using FF + GM, don't bother with all that rigamarole to load jQuery. GM now works with the later jQuery versions.
Just add a line like:
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
into your script's metadata block. jQuery will be copied once onto your local machine and run from there -- eliminating what can sometimes be a few seconds delay in your script's runtime.
And such scripts can run in Chrome, if you use one of the GM-emulating extensions like TamperMonkey.

Categories