Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use javascript to inject script references as needed?

I have a JS function that may occasionally get used on some pages. It is dependent on another JS file (swfObject.js), but I'd like to avoid having to include this file all over the place, as thats a wasted request most of the time.

Instead, I'd like to create a generic function that can inject a script reference into the page DOM as needed, so if this function is called, it would check for the script, and if it does not exist, load it in.

I'm fairly sure this is possible (and I'm not going to use document.write), but before I venture off into uncharted territory, has anyone done this before, and if so, any pointers?

EDIT: Ok, I tried it, and it works in IE6 and FF, I haven't tested other browsers yet.

Here is my code (Rev 2.0, now with optional callbacks):

function loadJSInclude(scriptPath, callback)
{
    var scriptNode = document.createElement('SCRIPT');
    scriptNode.type = 'text/javascript';
    scriptNode.src = scriptPath;

    var headNode = document.getElementsByTagName('HEAD');
    if (headNode[0] != null)
        headNode[0].appendChild(scriptNode);

    if (callback != null)    
    {
        scriptNode.onreadystagechange = callback;            
        scriptNode.onload = callback;
    }
}

and in the method with a dependency:

var callbackMethod = function ()
{
    // Code to do after loading swfObject
}

// Include SWFObject if its needed
if (typeof(SWFObject) == 'undefined')    
    loadJSInclude('/js/swfObject.js', callbackMethod);
else
    calbackMethod();

Any suggestions?

like image 563
FlySwat Avatar asked Oct 14 '08 22:10

FlySwat


People also ask

How do I create a dynamic script tag?

Dynamic loadingCreate a script element. Set the src , async , and type attributes. Append the script element to the body. Check if the file loaded or not in the load event.

How do you reference in JavaScript?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How do you inject a script in HTML?

Adding JavaScript into an HTML Document You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.

Can you use JavaScript in UiPath?

Inject Js Activity in UiPath executes JavaScript code in the context of the webpage corresponding to a UiElement. In my view, Inject Js is one of the most overlooked activities in UiPath. With a basic understanding of JavaScript, you can do various actions on a web page.


2 Answers

If you're using a higher level framework such as JQuery, you could check out the $.getScript(url, callback) function.

like image 187
abahgat Avatar answered Oct 30 '22 09:10

abahgat


If you want your code on the very next line and like to write something like:

if (iNeedSomeMore){
  Script.load("myBigCodeLibrary.js");  // includes code for myFancyMethod();
  myFancyMethod();                     // cool, no need for callbacks!
}

There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level.

If you use Prototype the Script.load method looks like this:

var Script = {
  _loadedScripts: [],
  include: function(script){
    // include script only once
    if (this._loadedScripts.include(script)){
      return false;
    }
    // request file synchronous
    var code = new Ajax.Request(script, {
      asynchronous: false, method: "GET",
      evalJS: false, evalJSON: false
    }).transport.responseText;
    // eval code on global level
    if (Prototype.Browser.IE) {
      window.execScript(code);
    } else if (Prototype.Browser.WebKit){
      $$("head").first().insert(Object.extend(
        new Element("script", {type: "text/javascript"}), {text: code}
      ));
    } else {
      window.eval(code);
    }
    // remember included script
    this._loadedScripts.push(script);
  }
};
like image 38
aemkei Avatar answered Oct 30 '22 11:10

aemkei