开发者

Conditional "Get Script File" in Javascript without using a library function

开发者 https://www.devze.com 2022-12-22 19:20 出处:网络
I work at a company that has many clients that have their own website that \"plugs in\" to our system. In other words they have their own website and they have a link that, when the user clicks it, tr

I work at a company that has many clients that have their own website that "plugs in" to our system. In other words they have their own website and they have a link that, when the user clicks it, transitions them over to our site.

There is a feature that I want to track by giving the client a small block of code to put on their homepage. Whenever the homepage is loaded with a certain query string variable I want the block of code to request a file on my server. Then on the server I'll record the tracking info based on the query string.

All this would be really easy if I can guarantee that the client would be using jQuery or some similar library, but there are a lot of clients and I can't really rely on them all using jQuery. At the same time I'd like to limit the size of the block of javascript code that they paste in.

I think the best solution would be to have something like:

if(querystring.substring("Tracking=") > 0)
{
   include("blah.aspx?TrackingQS=" + querystring);
}

but I can't find a include function in built-in javascript without calling some library like jQuery.

Any thoughts?? I could do straight up AJAX but I want to limit the number of lines of code for severa开发者_如何学Gol reasons that I won't bore you with here.


Add a script block programmatically

 function include(path) {
     var s = document.createElement('script'); 
     s.type = 'text/javascript'
     s.src = path;
     document.getElementsByTagName('head')[0].appendChild(s);
 }

As an enhancement, you can keep track of all the paths that have been added so that you dont accidentally load the same script twice.


Typically one does this by inserting a 1x1 img tag whose src is your blah.aspx.


Write a script that would use the built-in Ajax methods and give your clients this:

<script type="text/javascript" src="yourScript.js"></script>


You could give them something like this:

<script src="http://www.google.com/jsapi"></script>
<script>
    google.load("jquery", "1.4.1");
    ourJQ = jQuery.noconflict();
    //jQuery code
</script>

That will load jQuery from Google which will save them bandwidth and let you use jQuery.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号